gpt4 book ai didi

python - 如何使用 Python pandas 将某些列扩展为行

转载 作者:太空狗 更新时间:2023-10-30 01:44:16 27 4
gpt4 key购买 nike

我有一个包含多对多关系的两列的表。

例如

Animal     Food
rabbit grass
rabbit carrots
rabbit cabbage
dog carrots
horse grass
horse hay

我想要这样的东西:

Animal     Food1   Food2     Food3 
rabbit grass carrots cabbage
dog carrots
horse grass hay

或者类似这样的东西:

Animal     Grass     Carrots    Cabbage     Hay
rabbit True True True False
dog False True False False
horse True False False True

我已经尝试过数据透视表、熔化和堆叠,但仍然不知道如何执行此操作。任何帮助将不胜感激。谢谢!!

最佳答案

选项 1
groupbysize

df.groupby(['Animal', 'Food']).size().unstack(fill_value=0).astype(bool)

Food cabbage carrots grass hay
Animal
dog False True False False
horse False False True True
rabbit True True True False

s = df.groupby('Animal').Food.apply(list)
pd.DataFrame(s.values.tolist(), s.index).add_prefix('Food').fillna('')

Food0 Food1 Food2
Animal
dog carrots
horse grass hay
rabbit grass carrots cabbage

选项 2
groupbyvalue_counts

df.groupby('Animal').Food.value_counts().unstack(fill_value=0).astype(bool)

Food cabbage carrots grass hay
Animal
dog False True False False
horse False False True True
rabbit True True True False

选项 3
groupbystr.get_dummies

df.groupby('Animal').Food.apply('|'.join).str.get_dummies().astype(bool)

cabbage carrots grass hay
Animal
dog False True False False
horse False False True True
rabbit True True True False

选项 4
pandas.factorizenumpy.bincount

f1, u1 = pd.factorize(df.Animal.values)
f2, u2 = pd.factorize(df.Food.values)

n = u1.size
m = u2.size

b = np.bincount(f1 * m + f2, minlength=n * m).reshape(n, m)

pd.DataFrame(b.astype(bool), u1, u2)

grass carrots cabbage hay
rabbit True True True False
dog False True False False
horse True False False True

选项 5
无聊...所以想出了更多

f, u = pd.factorize(df.Animal.values)
n = u.size

a = [[] for _ in range(n)]
[a[i].append(food) for i, food in zip(f, df.Food)];
pd.DataFrame(a, u).rename(columns=lambda x: x+1).add_prefix('Food').fillna('')

Food1 Food2 Food3
rabbit grass carrots cabbage
dog carrots
horse grass hay

关于python - 如何使用 Python pandas 将某些列扩展为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44529018/

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