我的 DataFrame 看起来像这样:
A B 100 1 100 2 200 2 200 3
我需要找到 A 和 B 值的所有可能组合,并使用这些组合创建新的数据框,第三列指示原始 df 中存在的每个组合:
A B C 100 1 True 100 2 True 100 3 False 200 1 False 200 2 True 200 3 True
我现在是怎么做的:
import pandas as pd
df = pd.DataFrame({'A' : [100,100,200,200], 'B' : [1,2,2,3]})
df['D'] = 42
df2 = df[['A','D']].merge(df[['B','D']], on = 'D')
[['A','B']].drop_duplicates()
i1 = df.set_index(['A','B']).index
i2 = df2.set_index(['A','B']).index
df2['C'] = i2.isin(i1)
print(df2)
它有效,但看起来很丑。有更清洁的方法吗?
最佳答案
您可以使用:
- 创建填充
True
的新列 -
set_index
来自所有组合的列 - 创建
MultiIndex.from_product
来自df1
索引 -
reindex
原始df
如果不存在则添加False
s -
reset_index
对于MultiIndex
中的列
df['C'] = True
df1 = df.set_index(['A','B'])
mux = pd.MultiIndex.from_product(df1.index.levels, names=df1.index.names)
df = df1.reindex(mux, fill_value=False).reset_index()
print (df)
A B C
0 100 1 True
1 100 2 True
2 100 3 False
3 200 1 False
4 200 2 True
5 200 3 True
关于python - 两列可能组合的并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45635115/