2017-08-16 48 views
2

我有這樣一個數據幀:列表裏面大熊貓據幀細胞

enter image description here

,我想用它包含這樣的列表中的新列一個新的數據框: enter image description here

如何在包含基於類似月份的元素的數據框單元格內創建列表?

回答

4

讓嘗試,​​,groupbyapply(list)

df.set_index('month', append=True).groupby(level=[0,1,2], sort=False)['from']\ 
    .apply(list).reset_index('month') 

輸出:

   month from 
google 2016  2  [e] 
apple 2016  1 [b, c] 
     2016  3  [l] 
google 2016  3  [g] 
+1

不錯'set_index' :) – Wen

0

既然你沒有提供代碼只擅長例如屏幕截圖,知道這是可以通過索引添加列表作爲值的細胞,例如:

df.loc[index, column_name] = list[b, c] 

值的數據類型將對象

1

我的方法跟@ Scott的答案差不多,唯一不同的是沒有將單個值轉換成列表。

df.set_index('month', append=True).groupby(level=[0,1,2], sort=False)['from']\ 
     .apply(lambda x : x.tolist() if len(x)>1 else x.values[0]).reset_index('month') 

       month from 
google 2016  2  e 
apple 2016  1 [b, c] 
     2016  3  l 
google 2016  3  g 
2

Simpliest是大熊貓0.20.0+由水平和列一起使用新功能的GROUPBY:

df=df.groupby(['client','year','month'], sort=False)['from'].apply(list).reset_index('month') 
print (df) 
      month from 
client year    
google 2016  2  [e] 
apple 2016  1 [b, c] 
     2016  3  [l] 
google 2016  3  [g] 

對於一個元素列表的解決方案標量是類似Wen - 自定義函數與if else

df=df.groupby(['client','year','month'], sort=False)['from'] \ 
    .apply(lambda x: list(x) if len(x)>1 else x.iat[0]).reset_index('month') 
print (df) 
      month from 
client year    
google 2016  2  e 
apple 2016  1 [b, c] 
     2016  3  l 
google 2016  3  g 

而對於由,加入的字符串,則使用join而不是list

df=df.groupby(['client','year','month'], sort=False)['from'] 
    .apply(', '.join).reset_index('month') 
print (df) 
      month from 
client year    
google 2016  2  e 
apple 2016  1 b, c 
     2016  3  l 
google 2016  3  g