pandas :转换数据框以显示原始数据框中是否存在值的组合 [英] Pandas: Transform dataframe to show if a combination of values exists in the orignal Dataframe
问题描述
我有一个看起来像这样的数据框:
I have a Dataframe that looks like this:
| Col 1 | Col 2 |
0| A | 2 |
1| A | 3 |
2| B | 1 |
3| B | 2 |
并且我需要将其转换为一个数据框,以显示每个组合的第1列和第2列中的值(如果该组合包含在原始DataFrame中):
and I need to transform it into a Dataframe that shows for each combination, of the values in Col 1 and Col 2 if that combination is contained in the original DataFrame:
| 1 | 2 | 3 |
A |False|True |True |
B |True |True |False|
大熊猫中是否有本机转化方式? 我是手动创建转换后的Dataframe,但这是减慢速度的方法.
Is there a native way in pandas to get this transformation? I was creating the transformed Dataframe manually, but this is way to slow.
提前谢谢!
推荐答案
使用 get_dummies
与max
:
df = pd.get_dummies(df.set_index('Col 1')['Col 2'], dtype=bool).rename_axis(None).max(level=0)
print (df)
1 2 3
A False True True
B True True False
或者,如果可能的话,不丢失列Col2
中的值,然后使用 DataFrame.pivot
与 DataFrame.rename_axis
:
Or if possible not missing values in column Col2
then use DataFrame.pivot
with DataFrame.notna
, for remove index and columns name use DataFrame.rename_axis
:
df = df.pivot('Col 1', 'Col 2', 'Col 1').notna().rename_axis(index=None, columns=None)
print (df)
1 2 3
A False True True
B True True False
替代品可能重复,并且pivot
失败:
Alternative is possible duplicates and pivot
failed:
df = (df.pivot_table(index='Col 1', columns='Col 2', values='Col 1', aggfunc='size')
.notna()
.rename_axis(index=None, columns=None))
print (df)
1 2 3
A False True True
B True True False
或评论中的解决方案:
df = (pd.crosstab(df['Col 1'], df['Col 2'])
.gt(0)
.rename_axis(index=None, columns=None))
这篇关于 pandas :转换数据框以显示原始数据框中是否存在值的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!