[Python] Pandas之sort_values isin使用技巧

1.在pandas的DataFrame中,我们经常需要根据某属性来选取指定条件的行,这时isin方法就特别有效。

import pandas as pd
df = pd.DataFrame([[1,2,3],[1,3,4],[2,4,3]],index = ['one','two','three'],columns = ['A','B','C'])
print df
#        A  B  C
# one    1  2  3
# two    1  3  4
# three  2  4  3

这时假设我们选取A列中值为1的行,

mask = df['A'].isin([1]) #括号中必须为list
print mask
# one       True
# two       True
# three    False
# Name: A, dtype: bool
print df[mask]
#      A  B  C
# one  1  2  3
# two  1  3  4


2.pandas中的DataFrame如何按第一关键字,第二关键字对其进行排序,这里可以使用sort_values,老版本中为sort_index。

import pandas as pd
df = pd.DataFrame([[1,2,3],[2,3,4],[2,4,3],[1,3,7]],
                  index = ['one','two','three','four'],columns = ['A','B','C'])
print df
#        A  B  C
# one    1  2  3
# two    2  3  4
# three  2  4  3
# four   1  3  7
df.sort_values(by=['A','B'],ascending=[0,1],inplace=True)
print df
#        A  B  C
# two    2  3  4
# three  2  4  3
# one    1  2  3
# four   1  3  7



  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值