我有以下DataFrame。描述每个用户居住的城市

       City     Name
0   Seattle    Alice
1   Seattle      Bob
2  Portland  Mallory
3   Seattle  Mallory
4   Memphis      Bob
5  Portland  Mallory


您和熊猫一起可以实现以下目标吗?

     Name     City1    City2   City3
0   Alice     Seattle  NaN     Nan
1   Bob       Seattle  Memphis Nan
2   Mallory   Portland Seattle Portland


非常感谢你!

最佳答案

这是一种方法

In [619]: df.groupby('Name')['City'].apply(list).apply(pd.Series)
Out[619]:
                0        1         2
Name
Alice     Seattle      NaN       NaN
Bob       Seattle  Memphis       NaN
Mallory  Portland  Seattle  Portland


对于列名,使用renameformat

In [628]: (df.groupby('Name')['City'].apply(list).apply(pd.Series)
             .rename(columns=lambda x: 'City{}'.format(x+1)))
Out[628]:
            City1    City2     City3
Name
Alice     Seattle      NaN       NaN
Bob       Seattle  Memphis       NaN
Mallory  Portland  Seattle  Portland

关于python - 分组并整形长到宽格式的数据帧,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42231925/

10-11 04:11