pandas_2

作者: Canes | 来源:发表于2020-04-21 18:43 被阅读0次

DataFrame 数据结构

import pandas as pd
import numpy as np
  1. 通过ndarray构建

    arr = np.random(3,4)
    df = pd.DataFrame(arr)
    df.head()
    
  2. 通过dict构建

    dict_a = {
        "A" : 1,
        "B" : pd.Timestamp("20170426"),
        "C" : pd.Series(range(10, 14), dtype = "float64"),
        "D" : ["Python", "Java", "C++", "C"],
        "E" : np.array([3] * 4, dtype="int32"),
        "F" : "ITCast"
    }
    df = pd.DataFrame(dict_a)
    

Series对象

  1. 通过list

    lista = range(15,25)
    ser = pd.Series(lista)
    #ser = pd.Series(range(10, 15), index = ["a", "b", "c", "d", "e"]) #指定索引
    print(ser.values)  #查看值
    print(ser.index) #查看索引
    
    1. 通过字典
    dict_a = {1000 : "hello", 2000 : "world", 3000 : "!"}
    ser = pd.Series(dict_a)
    
    ser.index.name = 'class' #给索引添加名字
    ser.name = 'class_list' #给Series添加名字
    
    print(ser.values)  #查看值
    print(ser.index) #查看索引
    

索引操作

df_obj = pd.DataFrame(
        np.random.rand(5, 5),
        index = ["a", "b", "c", "d", "e"],
        columns = ['A', 'B','C','D','E']
    )
# 多维切片为 (行,列),单维按行,或者都按索引
# loc 按名称查找
# iloc 按照索引查找

print(df_obj.C)
print(df_obj['C'])
print(df_obj[[2]])
print(df_obj[["B", "D", "E"]])
print(df_obj[[1, 3, 4]])

print(ser_obj["b":"d"])
print(ser_obj.loc["b":"d"])
#print(df_obj['a':'c', 'D':'E'])
print(df_obj.loc['a':'c', 'D':'E'])
print(df_obj.loc['b', 'D'])

print(ser_obj[1:3])
print(ser_obj.iloc[1:3])
print(df_obj.iloc[1:3, 2:4])

apply

ser_obj = pd.Series(np.arange(10) + 10)
ser_obj.apply(lambda x:x+1)

df_obj = pd.DataFrame(np.random.randn(3, 4) - 10)
# 0 or ‘index’: apply function to each column
# 1 or ‘columns’: apply function to each row
df_obj.apply(lambda x:x.max())  
df_obj.apply(lambda x:x.max(),axis=1)

排序函数

  1. 按索引 sort_index()

    # Series
    ser_obj2 = pd.Series(range(10, 15), index = np.random.randint(20, size=5))
    ser_obj2.sort_index(ascending = False)
    
    # DataFrame
    df_obj2 = pd.DataFrame(np.random.rand(3, 4), 
                 index = np.random.randint(20, size= 3), 
                 columns = np.random.randint(20, size = 4))
     
    df_obj2.sort_index(ascending = False, axis = 1)  #按照列索引进行降序排序
    
    
    • df_obj2

                4         11        7         4 
      14  0.370184  0.509216  0.310019  0.728182
      19  0.442888  0.166256  0.682509  0.626576
      6   0.015395  0.160423  0.470271  0.865265
      
    • result:

                11        7         4         4 
      14  0.509216  0.310019  0.370184  0.728182
      19  0.166256  0.682509  0.442888  0.626576
      6   0.160423  0.470271  0.015395  0.865265
      
  2. 按值排序 sort_values()

    # series
    ser_obj3 = pd.Series(np.random.randint(10, 20, size=10))
    ser_obj3.sort_values()
    
    # dataframe
    df.sort_values(by=['col1']) #by指定列名
    

缺失数据处理

# 判断是否为NAN值,是则为True
df.isnull() 
# 去掉包含Nan行或者列,axis=1,去掉列
df.dropna(axis=1)
# 填充Nan数据
df.fillna(指定值)
# 去重
df['countries_en'].unique()

轴操作

import pandas as pd
import numpy as np
df = pd.DataFrame([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], columns=["col1", "col2", "col3", "col4"])

<img src="/Users/mac/Library/Application Support/typora-user-images/image-20200421103429975.png" width = "200" height = "80" div align=center />

print(df.mean(axis=0)) #axis为0,即逐行操作,列数不变
print('*'*20)
print(df.mean(axis=1)) #axis为1,即逐列操作,行数不变

df.apply(lambda x:x.min(),axis=0)
df.apply(lambda x:x.max(),axis=1)
image-20200421103429975.png
df.drop(['col1'],axis=1) #axis为1,删除列
df.drop(0,axis=0) #axis为0,删除行

分组

#1.分组操作,结果为groupby对象
dict_obj = {'key1' : ['a', 'b', 'a', 'b', 
                      'a', 'b', 'a', 'a'],
            'key2' : ['one', 'one', 'two', 'three',
                      'two', 'two', 'one', 'three'],
            'data1': np.random.randn(8),
            'data2': np.random.randn(8)}
df_obj = pd.DataFrame(dict_obj)
grouped = df.groupby("key2")

#2.分组运算,对groupby对象进行运算
grouped.sum()

#3.如果对单独某个数据部分的列进行分组运算,那么groupby的参数必须指定数据集的某一列进行分组
grouped2 = df["data2"].groupby(df["key1"])

#4.多层索引,索引顺序按列表里的参数顺序来决定
grouped3 = df.groupby(["key2", "key1"]).sum()

#5.按数据类型分组
df_obj.groupby(df.dtypes, axis = 1).size()

#6.自定义函数分组
def group_key(idx):
    return len(idx)
df.groupby(group_key,axis=1).sum()

聚合

dict_obj = {'key1' : ['a', 'b', 'a', 'b', 
                      'a', 'b', 'a', 'a'],
            'key2' : ['one', 'one', 'two', 'three',
                      'two', 'two', 'one', 'three'],
            'data1': np.random.randint(1,10, 8),
            'data2': np.random.randint(1,10, 8)}
df_obj = pd.DataFrame(dict_obj)

#1.内置聚合函数
df_obj.groupby("key1").sum()
# max(),min(),mean(),describe()

#2.自定义聚合函数
def func(num):
    return num.max()-num.min()
df.groupby("key2").agg(func)

#3.调用多个聚合函数做聚合运算
df.groupby("key1").agg(["sum", "mean", "max", func])

#4.每列作用不同的聚合函数
dict_mapping = {'data1':'mean',
                'data2':'sum'}
df.groupby('key1').agg(dict_mapping)

#5.一列使用多个聚合函数,参数是列表
dict_mapping = {'data1':'mean',
                'data2':['sum', 'mean', func]}
print(df.groupby('key1').agg(dict_mapping))

#6.添加列名前缀
df_sum = df.groupby("key2").sum().add_prefix("sum_")

合并

  1. merge

    pandas.merge(left, right, how='inner', on=None, left_on=None, right_on=None,
     left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'),         copy=True,indicator=False, validate=None)
    # left 左表
    # right 右表
    # how 连接方式
    # left_on 连接左字段
    # right_on 连接右字段
    # left_index 连接左索引
    # right_index 连接右索引
    
    def top_n(df_obj):
        # 返回根据APM排序后的结果的前3位数据
        return df_obj.sort_values(by="APM", ascending=False)[:3]
    
    # 对df_obj按LeagueIndex进行分组,并调用apple(top_n)
    sort_df = df_data.groupby("LeagueIndex").apply(top_n)
    ## 按照字段分组后每组的前三名数据
    
  2. concat

    pandas.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,        keys=None, levels=None, names=None, verify_integrity=False, sort=None,          copy=True)
    
    s1 = pd.Series(['a', 'b'])
    s2 = pd.Series(['c', 'd'])
    pd.concat([s1,s2],axis=0)
    pd.concat([s1,s2],axis=1)
    

数据清洗

  • 重复数据

    #保留数据出现顺序 由keep='first',取值可为 first,last,False
    #每一行和之前的行进行判断,如果和之前的行有重复,则返回True,否则为False
    df.duplicated()
    
    #过滤重复数据,如果某一行数据和之前有重复,则去除那一行,保留第一次出现数据
    df.drop_duplicates()
    df.drop_duplicates('column')  #指定列
    
    #替换多个数值,则第一个参数传入一个可迭代对象,包含所有需要替换的数值
    df.replace([4, 5], 100)  #4,5替换为100
    df.replace(regex=r'^ba.$', value='new') #可以用正则匹配
    

相关文章

  • pandas_2

    DataFrame 数据结构 通过ndarray构建arr = np.random(3,4)df = pd.Dat...

  • Pandas_2 数据排列

    1.实现任意两列数据之间四则运算以及创建新的列 new1 = data["column1"] +(-/*) dat...

网友评论

      本文标题:pandas_2

      本文链接:https://www.haomeiwen.com/subject/pfvpihtx.html