假设我有以下数据框:
#!/usr/bin/env python
import pandas as pd
df = pd.DataFrame([(1, 2, 1),
(1, 2, 2),
(1, 2, 3),
(4, 1, 612),
(4, 1, 612),
(4, 1, 1),
(3, 2, 1),
],
columns=['groupid', 'a', 'b'],
index=['India', 'France', 'England', 'Germany', 'UK', 'USA',
'Indonesia'])
print(df)
给出:
groupid a b
India 1 2 1
France 1 2 2
England 1 2 3
Germany 4 1 612
UK 4 1 612
USA 4 1 1
Indonesia 3 2 1
步骤1
此步骤可能不是必需的/与我想象的不同。实际上,我只对步骤2感兴趣,但是拥有它可以帮助我思考并解释我想要的。
我想按GroupID(df.groupby(df['groupid'])
)将数据分组并获得类似的内容:
groupid a b
1 [2] [1, 2, 3]
4 [1] [612, 1]
3 [2] [1]
步骤2
然后,我想找到所有在B列中只有一个条目的组ID,并且该条目等于1
。
同样,我想找到所有具有多个条目的组ID或一个不是1
的条目。
您可以比较 set
s,然后将索引值与 list
s:
mask = df.groupby('groupid')['b'].apply(set) == set([1])
print (mask)
groupid
1 False
3 True
4 False
Name: b, dtype: bool
i = mask.index[mask].tolist()
print (i)
[3]
j = mask.index[~mask].tolist()
print (j)
[1, 4]
新列使用map
:
df['new'] = df['groupid'].map(df.groupby('groupid')['b'].apply(set) == set([1]))
print (df)
groupid a b new
India 1 2 1 False
France 1 2 2 False
England 1 2 3 False
Germany 4 1 612 False
UK 4 1 612 False
USA 4 1 1 False
Indonesia 3 2 1 True
旧解决方案:
您可以将transform
与nunique
一起使用与原始DF相同的新Series
,因此可以将其与1
进行比较以获得唯一性,然后将另一种条件与1
进行比较:
mask = (df.groupby('groupid')['b'].transform('nunique') == 1) & (df['b'] == 1)
print (mask)
India False
France False
England False
Germany False
UK False
USA False
Indonesia True
Name: b, dtype: bool
对于list
S中的唯一值:
i = df.loc[mask, 'groupid'].unique().tolist()
print (i)
[3]
j = df.loc[~mask, 'groupid'].unique().tolist()
print (j)
[1, 4]
细节:
print (df.groupby('groupid')['b'].transform('nunique'))
India 3
France 3
England 3
Germany 2
UK 2
USA 2
Indonesia 1
Name: b, dtype: int64
iiuc您可以应用列表,并使用.str I.SE
检查长度temp = df.groupby('groupid')['b'].apply(list).to_frame()
temp
b
groupid
1 [1, 2, 3]
3 [1]
4 [612, 612, 1]
mask = (temp['b'].str.len() == 1) & (temp['b'].str[0] == 1)
temp[mask].index.tolist()
#[3]
temp[~mask].index.tolist()
#[1, 4]
我会选择
#group by the group id and than apply count for how many b entries are equal to 1
groups = df.groupby("groupid").apply(lambda group:len([x for x in
group["b"].values.tolist() if x == 1]))
#keep the groups containing 1 b equal to 1
groups = groups[groups == 1]
#print the indecies of the result (the groupid values)
print groups.index.values