python - 转置/反转 pandas 数据框的最简单方法是什么?

标签 python python-3.x pandas dataframe

我有以下 pandas 数据框:

Person     Item1      Item2     Item3     Item4
Adam       Apple      Eggs      Cookie
Alex       Chocolate  Orange    Eggs      Potato
Gina       Eggs       Apple     Orange    Milk

我想把它转换成这样:

Item      Count     Person1     Person2     Person3
Apple     2         Adam        Gina
Eggs      3         Adam        Alex        Gina
Cookie    1         Adam
Chocolate 1         Alex
Orange    2         Alex        Gina
Potato    1         Alex
Milk      1         Gina

我在发布之前已经彻底搜索了我的查询,但我没有找到任何匹配项(也许有更好的方法来重新表述我的问题)。如果这是重复的,我很抱歉,但如果是,请引导我到以前回答过这个问题的地方。

最佳答案

使用melt首先 reshape :

df = df.melt('Person', value_name='Item')
print (df)
   Person variable       Item
0    Adam    Item1      Apple
1    Alex    Item1  Chocolate
2    Gina    Item1       Eggs
3    Adam    Item2       Eggs
4    Alex    Item2     Orange
5    Gina    Item2      Apple
6    Adam    Item3     Cookie
7    Alex    Item3       Eggs
8    Gina    Item3     Orange
9    Adam    Item4        NaN
10   Alex    Item4     Potato
11   Gina    Item4       Milk

然后使用 GroupBy.size 聚合列表的自定义函数然后通过构造函数和join创建新的DataFrame计数列:

f = lambda x: x.tolist()
f.__name__ = 'Person'
df1 = df.groupby('Item', sort=False)['Person'].agg([f, 'size'])

df2 = pd.DataFrame(df1.pop('Person').values.tolist(), index=df1.index).add_prefix('Person')
df3 = df1.join(df2).reset_index()
print (df3)
        Item  size Person0 Person1 Person2
0      Apple     2    Adam    Gina    None
1  Chocolate     1    Alex    None    None
2       Eggs     3    Gina    Adam    Alex
3     Orange     2    Alex    Gina    None
4     Cookie     1    Adam    None    None
5     Potato     1    Alex    None    None
6       Milk     1    Gina    None    None

关于python - 转置/反转 pandas 数据框的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52053478/

相关文章:

python - 我有三个单独的列表,我想按顺序连接它们

python - 我怎样才能调出一个带有已经用 python 脚本导入的包的 python shell?

python - 按行的绝对值对数据帧进行排序

python - 情节不会在 Jupyter 中显示

python - 遍历 Pandas 数据框的行

python - 根据值拆分 pandas 数据框

python - 子模块上出现 ModuleNotFoundError

python - 如何限制运行脚本的权限?

python - 将 json 文件读取为 pandas 数据框?

python - 使用 groupby 创建新数据框