2017-02-14 39 views
2

我有以下DataFrame。描述每個用戶居住的城市Groupby並重新整形爲寬格式的數據幀

 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 

非常感謝!

回答

1

Here'e單程

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 
1

您可以通過以下方式做到這一點:

  1. 檢索的累積計數分組在名稱。要根據需要格式化標題,請在得到的結果值中加1,因爲它開始分配從0到1的組。使用map通過在這些字符的開頭添加"City" char來格式化字符串。
  2. 用上述得到的結果作爲索引軸和unstackDF沿着設置名稱。此外,使用fill_value參數,None值可由NaN取代。

cc = df.groupby('Name')['City'].cumcount().add(1).map('City{}'.format) 
df.set_index(['Name', cc])['City'].unstack(fill_value=np.nan).reset_index() 

enter image description here

相關問題