Groupby 并将长格式数据框重塑为宽格式数据框

Agu*_*lar 5 python bigdata dataframe pandas

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

       City     Name
0   Seattle    Alice
1   Seattle      Bob
2  Portland  Mallory
3   Seattle  Mallory
4   Memphis      Bob
5  Portland  Mallory
Run Code Online (Sandbox Code Playgroud)

你能用 pandas 实现以下目标吗?

     Name     City1    City2   City3
0   Alice     Seattle  NaN     Nan
1   Bob       Seattle  Memphis Nan
2   Mallory   Portland Seattle Portland
Run Code Online (Sandbox Code Playgroud)

非常感谢!

Zer*_*ero 6

这是一种方法

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
Run Code Online (Sandbox Code Playgroud)

对于列名称,请使用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
Run Code Online (Sandbox Code Playgroud)