参考文献

pandas

Series

  • Series 是个定长的字典序列.说是定长是因为在存储的时候,相当于两个 ndarray,这也是和字典结构最大的不同.因为在字典的结构里,元素的个数是不固定的.
  • Series有两个基本属性:index 和 values.在 Series 结构中,index 默认是 0,1,2,……递增的整数序列,当然也可以自己来指定索引,比如 index=[‘a’, ‘b’, ‘c’, ‘d’].
1
2
3
4
5
6
7
8
9
10
11
12
import pandas as pd
from pandas import Series, DataFrame

x1 = Series([1, 2, 3, 4])
x2 = Series(data=[1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
print(x1)
print(x2)

# 采用字典形式创建Series
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
x3 = Series(d)
print(x3)

DataFrame

  • DataFrame类型数据结构类似数据库表.
  • 它包括了行索引和列索引,可以将DataFrame看成是由相同索引的 Series 组成的字典类型.
1
2
3
4
5
6
7
8
9
10
11
import pandas as pd
from pandas import Series, DataFrame

data = {'Chinese': [66, 95, 93, 90, 80], 'English': [65, 85, 92, 88, 90],
'Math': [30, 98, 96, 77, 90]}
df1 = DataFrame(data)
df2 = DataFrame(data, index=['ZhangFei', 'GuanYu', 'ZhaoYun', 'HuangZhong', 'DianWei'],
columns=['English', 'Math', 'Chinese'])
print(df1)
print(df2)

数据导入和输出

1
2
3
4
5
import pandas as pd
from pandas import Series, DataFrame

data = DataFrame(pd.read_excel('data.xlsx'))
data.to_excel('data1.xlsx')

数据清洗

删除 DataFrame 中的不必要的列或行
  • Pandas 提供了一个便捷的方法 drop() 函数来删除不想要的列或行

    1
    2
    3
    df2 = df2.drop(columns=['Chinese'])

    df2 = df2.drop(index=['ZhangFei'])
重命名列名 columns,让列表名更容易识别
  • 如果想对DataFrame中的columns进行重命名,可以直接使用rename(columns=new_names, inplace=True)函数

    1
    df2.rename(columns={'Chinese': 'YuWen', 'English': 'Yingyu'}, inplace = True)
去重复的值
1
2
df = df.drop_duplicates() # 去除重复行

更改数据格式
  • 可以使用astype函数来规范数据格式,比如把Chinese 字段的值改成str类型,或者int64

    1
    2
    df2['Chinese'].astype('str') 
    df2['Chinese'].astype(np.int64)
删除数据间的空格
  • 使用strip函数

    1
    2
    3
    4
    5
    6
    # 删除左右两边空格
    df2['Chinese']=df2['Chinese'].map(str.strip)
    # 删除左边空格
    df2['Chinese']=df2['Chinese'].map(str.lstrip)
    # 删除右边空格
    df2['Chinese']=df2['Chinese'].map(str.rstrip)
  • 如果数据里有某个特殊的符号,同样可以使用strip函数,比如 Chinese 字段里有美元符号,想把这个删掉,可以这么写:

    1
    df2['Chinese']=df2['Chinese'].str.strip('$')
大小写转换
  • 在 Python 里直接使用upper(), lower(), title()函数

    1
    2
    3
    4
    5
    6
    7

    # 全部大写
    df2.columns = df2.columns.str.upper()
    # 全部小写
    df2.columns = df2.columns.str.lower()
    # 首字母大写
    df2.columns = df2.columns.str.title()
查找空值
  • 数据量大的情况下,有些字段存在空值NaN的可能,这时就需要使用 Pandas 中的isnull函数进行查找
  • 如果想看下哪个地方存在空值NaN,可以针对数据表df进行df.isnull()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import pandas as pd
from pandas import Series, DataFrame

df = DataFrame(pd.read_excel('/Users/holelin/data/pandas_test/untitled.xlsx'))
print(df.isnull())
print(df.isnull().any())

# output
姓名 语文 英语 数学
0 False False False True
1 False False False False
2 False False False False
3 False False False False
4 False False False False
姓名 False
语文 False
英语 False
数学 True
数据清洗
  • 使用apply函数对数据进行清洗

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    # 对 name 列的数值都进行大写转化
    df['name'] = df['name'].apply(str.upper)


    def double_df(x):
    return 2*x
    df1[u'语文'] = df1[u'语文'].apply(double_df)


    def plus(df,n,m):
    df['new1'] = (df[u'语文']+df[u'英语']) * m
    df['new2'] = (df[u'语文']+df[u'英语']) * n
    return df
    df1 = df1.apply(plus,axis=1,args=(2,3,))

数据统计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import pandas as pd
from pandas import Series, DataFrame

df = DataFrame(pd.read_excel('/Users/holelin/data/pandas_test/untitled.xlsx'))
print(df.isnull())
print(df.isnull().any())
# 一次性输出多个统计指标,包括:count,mean,std,min,max等
print(df.describe())
# 统计个数,空值 NaN不计算
print(df.count())
# 最小值 最大值 总和 平均数 中位数 方差 标准差
print(df[u'语文'].min())
print(df[u'语文'].max())
print(df[u'语文'].sum())
print(df[u'语文'].mean())
print(df[u'语文'].median())
print(df[u'语文'].var())
print(df[u'语文'].std())

print("统计最小值的索引位置: " + str(df[u'语文'].argmin()))
print("统计最大值的索引位置: " + str(df[u'语文'].argmax()))
print("统计最小值的索引值: " + str(df[u'语文'].idxmax()))
print("统计最大值的索引值: " + str(df[u'语文'].idxmin()))

数据表合并

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import pandas as pd
from pandas import Series, DataFrame

df1 = DataFrame({'name': ['ZhangFei', 'GuanYu', 'a', 'b', 'c'], 'data1': range(5)})
df2 = DataFrame({'name': ['ZhangFei', 'GuanYu', 'A', 'B', 'C'], 'data2': range(5)})
print(df1)
print(df2)
# 基于指定列进行连接
df3 = pd.merge(df1, df2, on='name')
print(df3)

# inner内连接
df3 = pd.merge(df1, df2, how='inner')
print(df3)

# left 左连接
df3 = pd.merge(df1, df2, how='left')
print(df3)

# right 右连接
df3 = pd.merge(df1, df2, how='right')
print(df3)

# outer 外连接
df3 = pd.merge(df1, df2, how='outer')
print(df3)


name data1
0 ZhangFei 0
1 GuanYu 1
2 a 2
3 b 3
4 c 4

name data2
0 ZhangFei 0
1 GuanYu 1
2 A 2
3 B 3
4 C 4

name data1 data2
0 ZhangFei 0 0
1 GuanYu 1 1

name data1 data2
0 ZhangFei 0 0
1 GuanYu 1 1

name data1 data2
0 ZhangFei 0 0.0
1 GuanYu 1 1.0
2 a 2 NaN
3 b 3 NaN
4 c 4 NaN

name data1 data2
0 ZhangFei 0.0 0
1 GuanYu 1.0 1
2 A NaN 2
3 B NaN 3
4 C NaN 4

name data1 data2
0 ZhangFei 0.0 0.0
1 GuanYu 1.0 1.0
2 a 2.0 NaN
3 b 3.0 NaN
4 c 4.0 NaN
5 A NaN 2.0
6 B NaN 3.0
7 C NaN 4.0
pandasql
  • pandasql 中的主要函数是 sqldf,它接收两个参数:一个 SQL 查询语句,还有一组环境变量 globals()locals()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import pandas as pd
    from pandas import DataFrame
    from pandasql import sqldf, load_meat, load_births
    df1 = DataFrame({'name':['ZhangFei', 'GuanYu', 'a', 'b', 'c'], 'data1':range(5)})
    pysqldf = lambda sql: sqldf(sql, globals())
    sql = "select * from df1 where name ='ZhangFei'"
    print pysqldf(sql)

    # output
    name data1
    0 ZhangFei 0