[英]There's any easy way to find a value in a column with two selected repeated values in other column?
我的问题是,我有一个这样的数据框:
一个 | 乙 |
---|---|
一个 | 1 |
b | 1 |
c | 3 |
d | 1 |
一个 | 2 |
b | 2 |
d | 2 |
我希望在 A 中找到在 B 中具有值为 1 和 2 的条目的值。这个问题的答案应该是 A 中唯一值是 a、b 和 d 的值(或行)。 应排除具有值 c 的行。 请记住,真正的数据集更复杂,是一张销售表,我只想列出在第 1 个月和第 2 个月同时购买的客户。
提前致谢。 我以一种非常丑陋和不具表现力的方式解决了这个问题,我希望有一种更好、更清洁的方式来做到这一点。
您可以创建一个掩码,仅保留 B 为1
或2
的行,第二部分仅保留至少具有单行为1
和2
的组。 如果你想用np.logical_and.reduce
来节省一些写作,你可以缩放它。
import numpy as np
mask = (df['B'].isin([1, 2])
& df['B'].eq(1).groupby(df['A']).transform('any')
& df['B'].eq(2).groupby(df['A']).transform('any'))
df[mask]
A B
0 a 1
1 b 1
3 d 1
4 a 2
5 b 2
6 d 2
更可扩展,只需将值添加到列表中:
import numpy as np
vals = [1, 2]
mask = (df['B'].isin(vals)
& np.logical_and.reduce([df['B'].eq(val).groupby(df['A']).transform('any')
for val in vals]))
我相信你可以使用groupby.transform
和loc
,就好像我得到你你的要求很简单:
import pandas as pd
res = (df.loc[df.groupby('A')['B'].transform('size')>=2]).sort_values(by='A')
A B
0 a 1
4 a 2
1 b 1
5 b 2
3 d 1
6 d 2
已经有很多很好的答案,这是我解决问题的方法
import pandas as pd
# Setup
A = ["a", "b", "c", "d", "a", "b", "d"]
B = [1, 1, 3, 1, 2, 2, 2]
df = pd.DataFrame({"A": A, "B": B})
# Keep only values less than or equal than 2, representing month 1 and 2
filter = df[df["B"] <= 2]
# Sort the values by column A and B
sort = df.sort_values(by=["A", "B"])
# Group them and count number of appeareances
groupby_count = sort.groupby(["A"], as_index=False).agg(count=("A", "count"))
# Only keep appearances equal to 2, as that would imply appearances of month 1 and 2
print(groupby_count[groupby_count["count"] == 2])
output:
A count
0 a 2
1 b 2
3 d 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.