gpt4 book ai didi

python - 使用数据内容作为python中的列创建一个表

转载 作者:太空宇宙 更新时间:2023-11-03 23:52:37 26 4
gpt4 key购买 nike

我目前有这样的原始数据:

person1  person2   person3...
blue red green
red blue yellow
black black
white green
orange

有很多不同的值和列。

我需要的是:

         Blue  Red  Black  Green Yellow Orange White
Person1 Y Y Y Y Y
Person2 Y Y Y Y
Person3 Y Y

有什么建议吗?

谢谢

最佳答案

方法一:DataFrame.apply + pd.value_counts

new_df=df.apply(pd.value_counts).replace({1:'Y',np.nan:''}).T
print(new_df)

black blue green orange red white yellow
person1 Y Y Y Y Y
person2 Y Y Y Y
person3 Y Y

方法二:pd.crosstab + DataFrame.melt

df2=df.melt()
new_df=pd.crosstab(df2['variable'],df2['value']).replace({0:'',1:'Y'}).rename_axis(index=None,columns=None)
print(new_df)
black blue green orange red white yellow
person1 Y Y Y Y Y
person2 Y Y Y Y
person3 Y Y

关于python - 使用数据内容作为python中的列创建一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58845705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com