pandas遇到的问题汇总

join()

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'],
... 'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})
>>> df
key A
0 K0 A0
1 K1 A1
2 K2 A2
3 K3 A3
4 K4 A4
5 K5 A5
>>> other = pd.DataFrame({'key': ['K0', 'K1', 'K2'],
... 'B': ['B0', 'B1', 'B2']})
>>> other
key B
0 K0 B0
1 K1 B1
2 K2 B2

Join DataFrames using their indexes.

1
2
3
4
5
6
7
8
>>> df.join(other, lsuffix='_caller', rsuffix='_other')
key_caller A key_other B
0 K0 A0 K0 B0
1 K1 A1 K1 B1
2 K2 A2 K2 B2
3 K3 A3 NaN NaN
4 K4 A4 NaN NaN
5 K5 A5 NaN NaN

如果不想以现有index为基础去Join,比如上面的例子想用key这个index去Join,可以:

1
2
3
4
5
6
7
8
>> df.join(other.set_index('key'), on='key')
key A B
0 K0 A0 B0
1 K1 A1 B1
2 K2 A2 B2
3 K3 A3 NaN
4 K4 A4 NaN
5 K5 A5 NaN

merge()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
df1 = pd.DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'],
'value': [1, 2, 3, 5]})
df2 = pd.DataFrame({'rkey': ['foo', 'bar', 'baz', 'foo'],
'value': [5, 6, 7, 8]})
df1
lkey value
0 foo 1
1 bar 2
2 baz 3
3 foo 5
df2
rkey value
0 foo 5
1 bar 6
2 baz 7
3 foo 8


选择多列

有时候需要选择DataFrame中的多个列组成一个新的DataFrame,这时候要用

1
df[['column1','column2']] # 注意这里是双层中括号!

drop 满足条件的行

1
2
3
df_clear = df.drop(df[df['x']<0.01].index)
# 也可以使用多个条件
df_clear = df.drop(df[(df['x']<0.01) | (df['x']>10)].index) #删除x小于0.01或大于10的行

dropna 丢掉某一列中有空的行

1
df.dropna(subset=['column_name'])

apply,applymap,map

apply

官方解释是 apply a function along an axis of the dataframe.

apply内函数的是Series,也就是在Series上做函数操作。index可以是dataframe的index,也可以是dataframe的columns(axis=1)。axis=0时,apply the function to each column,也就是每一列为一个整体去实施函数。axis=1时,每一行作为一个整体去实施函数。

1
2
df.apply(np.sum, axis=0)
df.apply(np.sum, axis=1)

applymap

官方解释是 apply a function to a dataframe elementwise.和apply不一样的是对dataframe中每一个元素分别作函数。

applymap允许实施一个函数,这个函数接受和返回的都是一个标量。

1
df.applymap(lambda x: len(str(x)))

map

map调用的对象只能是Series,而上面两个方法的调用对象是Dataframe。