pandas基本操作

1. pandas DataFrame对象的创建

1
2
dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))

2. 操作数据

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
df.head()
df.tail(3)
df.index
df.describe()
# 单列索引
df.iloc[1:2,2:]
# 特定索引
df.iloc[[1,2],[2,3]]
# 布尔索引
df[df>0.5] = 1
# 赋值列
df2['E'] = ['A,','B','C','E','3','3']
# 赋值行
df2.loc['e'] = [1,2,3,4,5]
#访问某个位置
df2.iat[0,1]
#删除带有缺失值的行
df1.dropna(how = 'any')
#填充空数据
df1.fillna(value=5)
# 获得每一列的平均值、
df1.mean()
# 获得每一行的平均值
df1.mean(1)
# 修改行标签
df1.index = ['A','B','C']
#修改行列
data.rename(index={'A':'D', 'B':'E', 'C':'F'}, columns={'a':'d','b':'e','c':'f'}, inplace = True)
#连接两个表
pe = [df1,df2]
pd.concat(pe)
#数据库连接风格
left = pd.DataFrame({'key': ['foo', 'foo'], 'lval': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'foo'], 'rval': [4, 5]})
pd.merge(left, right, on='key')
#写入文件
df1.to_csv('foo.csv')
Donate comment here