在pandas Dataframe

时间:2017-07-21 05:18:40

标签: python pandas

我有一个DataFrame说(df),其中列状态城市密码

我可以在这样的状态下为特定城市选择所有行。

requiredState = 'ABC'
requiredCity  = 'XYZ'

newDf = df[ (df['city']== requiredCity) & (df['state']==requiredState) ]

现在我想为所有状态的城市选择所有行。

所以这可以通过简单地删除城市条件来完成,如:

newDf = df[ (df['state'] == requiredState) ]

这将给我一个州的所有城市。

我的问题是,是否有一些方法 我不需要删除城市状况,这将导致一个州的所有城市?

即。

之类的东西
requiredCity = ALL
nDf = df[ (df['city']== requiredCity) & (df['state']==requiredState) ]

或者我们可以传递所需城市的列表而不是ALL吗?

requiredCity = ['city1','city2']

2 个答案:

答案 0 :(得分:3)

我认为您需要isin,但requiredCity必须位于list,因此可以添加与|(或)原始条件链接的新条件:

df = pd.DataFrame({'city':list('abcdef'),
                   'pincode':[4,5,4,5,5,4],
                   'state':list('aaabbb')})

print (df)
  city  pincode state
0    a        4     a
1    b        5     a
2    c        4     a
3    d        5     b
4    e        5     b
5    f        4     b


requiredState = 'a'
requiredCity = ['ALL']

m1 = ('ALL' in requiredCity) | (df['city'].isin(requiredCity))
m2 = (df['state']==requiredState)
newDf = df[m1 & m2]
print (newDf)
  city  pincode state
0    a        4     a
1    b        5     a
2    c        4     a
requiredState = 'a'
requiredCity = ['a','c']

m1 = ('ALL' in requiredCity) | (df['city'].isin(requiredCity))
m2 = (df['state']==requiredState)
newDf = df[m1 & m2]
print (newDf)
  city  pincode state
0    a        4     a
2    c        4     a
requiredState = 'a'
requiredCity = ['a']

m1 = ('ALL' in requiredCity) | (df['city'].isin(requiredCity))
m2 = (df['state']==requiredState)
newDf = df[m1 & m2]
print (newDf)
  city  pincode state
0    a        4     a

答案 1 :(得分:1)

 requiredCity = ['city1', 'city2']
 df[(df['city'].apply(lambda x : x in requiredCity)) & (df['state'] == requiredState)]