我的数据框架如下所示:
┌────┬──────┬──────┐
│ No │ col1 │ col2 │
├────┼──────┼──────┤
│ 1 │ A │ 5.0 │
│ 1 │ B1 │ 10.0 │
│ 1 │ B2 │ 20.0 │
│ 2 │ A │ 0.0 │
│ 2 │ B1 │ 0.0 │
│ 2 │ C1 │ 0.0 │
│ 3 │ A │ 0.0 │
│ 3 │ B1 │ 5.0 │
│ 3 │ C1 │ 20.0 │
│ 3 │ C2 │ 30.0 │
└────┴──────┴──────┘
首先,我使用groupby
对数据帧按列编号进行分组。
我现在想做三件事:
col2 == 0.0
值列表(在本例中为第2号)col2 != 0.0
for col1 == 'A'
)的列表,但组中至少有一个行具有col2 == 0.0
(在本例中为第3行)col2 == 0.0
的No's列表(第2和第3行)很抱歉一次问了三个问题。希望这样可以。
谢谢您:)
发布于 2018-04-15 05:25:57
您可以使用:
g = df['col2'].eq(0).groupby(df['No'])
a = g.all()
a = a.index[a].tolist()
print (a)
[2]
b1 = (df['col2'].ne(0) & df['col1'].eq('A')).groupby(df['No']).any()
b2 = (df['col2'].eq(0) & df['col1'].ne('A')).groupby(df['No']).any()
b = b1 & b2
b = b.index[b].tolist()
print (b)
[]
c = g.any()
c = c.index[c].tolist()
print (c)
[2,3]
另一种解决方案应该是自定义函数,用于返回布尔型DataFrame
和包含3个列表的最终创建字典:
def f(x):
a = x['col2'].eq(0)
b1 = x['col2'].ne(0) & x['col1'].eq('A')
b2 = a & x['col1'].ne('A')
b = b1.any() & b2.any()
return pd.Series([a.all(), b, a.any()], index=list('abc'))
m = df.groupby('No').apply(f)
print (m)
a b c
No
1 False False False
2 True False True
3 False False True
fin = {x: m[x].index[m[x]].tolist() for x in m.columns}
print (fin)
{'a': [2], 'b': [], 'c': [2, 3]}
https://stackoverflow.com/questions/49842343
复制