脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 对pandas中iloc,loc取数据差别及按条件取值的方法详解

对pandas中iloc,loc取数据差别及按条件取值的方法详解

2021-04-16 00:10tomato_guo Python

今天小编就为大家分享一篇对pandas中iloc,loc取数据差别及按条件取值的方法详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

Dataframe使用loc取某几行几列的数据:

?
1
print(df.loc[0:4,['item_price_level','item_sales_level','item_collected_level','item_pv_level']])

结果如下,取了index为0到4的五行四列数据。

?
1
2
3
4
5
6
  item_price_level item_sales_level item_collected_level item_pv_level
0     3     3      4    14
1     3     3      4    14
2     3     3      4    14
3     3     3      4    14
4     3     3      4    14

而使用iloc,如下所示:

?
1
print(df.iloc[0:4,6:9])

结果如下,取得是index为0到3四行,以及第6到8列(从0列开始)3列数据。

?
1
2
3
4
5
  item_price_level item_sales_level item_collected_level
0     3     3      4
1     3     3      4
2     3     3      4
3     3     3      4

另外loc可以按条件取数据:

?
1
2
print(df.loc[df.item_price_level==0,:])
print(df.loc[df[item_price_level]==0,:])

上面两条语句效果是一样的,都是取item_price_level为0的所有数据。可以把冒号改成几列列名,只取满足条件的某几列数据:

?
1
print(df.loc[df['item_price_level']==0,['item_price_level','item_sales_level']])

结果前两行如下:

?
1
2
3
   item_price_level item_sales_level
129141     0    10
129142     0    10

条件为多个时 (同时满足两个条件如下):

?
1
print(df.loc[(item_price_level==0) & (item_sales_level==3),:])

以上这篇对pandas中iloc,loc取数据差别及按条件取值的方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_28811329/article/details/79961800

延伸 · 阅读

精彩推荐