pandas Cookbook 第一讲 ——习惯用法

所谓的Cookbook,原意为菜谱。在这里引申为Pandas一些有用的案例和链接(stack-over-flow,Github)的合辑。
在接下来的教程中,pandas 和 numpy 是仅有的两个被引入的两个模块,余下的会在需要时显式导入。
本教程是在python3.4版本下编写执行,早期python版本可能需要细微调整


  • 习惯用法
###这里有一些pandas简介的习惯用法
#### if-then/if-then-else 作用在列上,并赋值给另外一列或者多列
import pandas as pd
import numpy as np

df=pd.DataFrame({'AAA':[4,5,6,7],'BBB':[10,20,30,40],'CCC':[100,50,-30,-50]})
df
AAA BBB CCC
0 4 10 100
1 5 20 50
2 6 30 -30
3 7 40 -50

#### if-then... 

##### if-then作用在一列(如果AAA列大于等于5,BBB列则被赋值为-1) 

df.ix[df.AAA>=5,'BBB']=-1 

df

AAA BBB CCC
0 4 10 100
1 5 -1 50
2 6 -1 -30
3 7 -1 -50
# 接下来是if-then作用到多列上(如果AAA大于等于5,BBB,CCC两列均被赋值为555)
 df.ix[df.AAA>=5,['BBB','CCC']]=555 df
AAA BBB CCC
0 4 10 100
1 5 555 555
2 6 555 555
3 7 555 555
#### 如果不满足以上条件,那就相当于else 
df.ix[df.AAA<5,['BBB','CCC']]=2000 df 
AAA BBB CCC
0 4 2000 2000
1 5 555 555
2 6 555 555
3 7 555 555
#### 或者我们可以设置一个遮罩(mask),学过ps的同学应该有直观印象,没学过望文生义也能猜个差不多 
df_mask=pd.DataFrame({'AAA':[True]*4,'BBB':[False]*4,'CCC':[True,False]*2}) 
df.where(df_mask,-1000)
 ####遮罩为False的都被赋值为-1000 ```



|  | AAA | BBB | CCC |
| --- | --- | --- | --- |
| 0 | -100 | -100 | 2000 |
| 1 | -100 | -100 | -100 |
| 2 | -100 | -100 | 555 |
| 3 | -100 | -100 | -100 |



```python 
#### if-then-else 用numpy的where() 
df=pd.DataFrame({'AAA':[4,5,6,7],'BBB':[10,20,30,40],'CCC':[100,50,-30,-50]}) 
df['logic']=np.where(df['AAA']>5,'high','low') 
df 
AAA BBB CCC logic
0 4 10 100 low
1 5 20 50 low
2 6 30 -30 high
3 7 40 -50 high

你可能感兴趣的:(pandas Cookbook 第一讲 ——习惯用法)