pandas官方文档中cookbook(1)的idioms的翻译
来源:互联网 发布:linux tmp 手动清理 编辑:程序博客网 时间:2024/05/22 01:30
python代码风格
文档版本:0.20.3
这些例子是用python3.4写出来的。对于较早的python版本需要对代码做些相应的调整。
Pandas(pd)和Numpy(np)是唯一两个默认导入的包。其余的包会显示导入给新用户看。
若有翻译不当的地方,请多多指教。
这份文档中的例子都是从Stack-Overflow和Github中别人提问的比较经典的问题
这里有一些pandas整洁的代码书写风格。
对一列进行逻辑判断,然后作用与其他列上。
http://stackoverflow.com/questions/17128302/python-pandas-idiom-for-if-then-else
In [1]: df = pd.DataFrame(...: {'AAA' : [4,5,6,7], 'BBB' : [10,20,30,40],'CCC' : [100,50,-30,-50]}); df...: Out[1]: AAA BBB CCC0 4 10 1001 5 20 502 6 30 -303 7 40 -50
if-then
对一列进行判断然后作用在另一列上
In [2]: df.loc[df.AAA >= 5,'BBB'] = -1; dfOut[2]: AAA BBB CCC0 4 10 1001 5 -1 502 6 -1 -303 7 -1 -50
对一列进行判断然后作用在另外两列上
In [3]: df.loc[df.AAA >= 5,['BBB','CCC']] = 555; dfOut[3]: AAA BBB CCC0 4 10 1001 5 555 5552 6 555 5553 7 555 555
对其他行进行不同的逻辑判断,下面类似于else操作。
In [4]: df.loc[df.AAA < 5,['BBB','CCC']] = 2000; dfOut[4]: AAA BBB CCC0 4 2000 20001 5 555 5552 6 555 5553 7 555 555
或者在你建立了一个布尔值的数据框时,你可以使用pandas的where函数来对各列进行逻辑判断。
In [5]: df_mask = pd.DataFrame({'AAA' : [True] * 4, 'BBB' : [False] * 4,'CCC' : [True,False] * 2})In [6]: df.where(df_mask,-1000)Out[6]: AAA BBB CCC0 4 -1000 20001 5 -1000 -10002 6 -1000 5553 7 -1000 -1000
使用numpy的where函数对列进行逻辑判断
http://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column
In [7]: df = pd.DataFrame(...: {'AAA' : [4,5,6,7], 'BBB' : [10,20,30,40],'CCC' : [100,50,-30,-50]}); df...: Out[7]: AAA BBB CCC0 4 10 1001 5 20 502 6 30 -303 7 40 -50In [8]: df['logic'] = np.where(df['AAA'] > 5,'high','low'); dfOut[8]: AAA BBB CCC logic0 4 10 100 low1 5 20 50 low2 6 30 -30 high3 7 40 -50 high
阅读全文
0 0
- pandas官方文档中cookbook(1)的idioms的翻译
- pandas官方文档中cookbook(2)的split&building criteria翻译
- pandas官方文档cookbook(5)中MissValue&groupby翻译
- pandas官方文档中cookbook(3)的selection&new column&multiindexing翻译
- pandas官方文档cookbook(4)中Arithmetic&Slicing&Sorting翻译
- pandas官方文档cookbook(6)中Split&Pivot&Apply翻译
- 十分钟掌握pandas(pandas官方文档翻译)
- 十分钟搞定pandas(官方学习文档的译文)
- FMDB官方文档的翻译
- 对官方文档中NSAutoreleasePool的个人翻译
- runspec 的选项说明(spec2006官方文档的翻译)
- Fragment的用法(官方文档的翻译)
- 翻译下Mini-XML官方提供的帮助文档1
- Android Geofence的学习(一)翻译官方文档
- Android Geofence的学习(二)继续翻译官方文档
- Android Geofence的学习(一)翻译官方文档
- FMDB官方文档-GCD的使用-提高性能(翻译)
- Retrofit 2.0非常简单的入门(翻译官方文档)
- HDU-4453 Looploop(Splay树)
- Android初级——Reflect简单使用
- HDU 1050 Moving Tables
- C#日期时间格式化
- Linux中fork()函数的底层实现
- pandas官方文档中cookbook(1)的idioms的翻译
- 清除浮动产生的问题
- java.toString() ,(String),String.valueOf区别
- Python的诡异陷阱
- hdu3507 斜率优化dp入门
- 理解线程池的原理
- MySQL函数大全及用法示例
- scala中的函数组合器map,foreach,flatmap,flatten,filter,zip等用法
- 2.创建和删除数据库实例