2017-04-24 95 views
2

我在這個格式的熊貓數據幀:特定組通過熊貓

id Role time text   
id1 A  t1 text1   
id1 B  t2 text2   
id1 B  t3 text3   
id1 A  t4 text4   
id1 B  t5 text5   
id1 A  t6 text6   
id1 A  t7 text7   
id2 A  t8 text8   
id2 B  t9 text9   
id2 B  t10 text1   
id2 B  t11 text10  
id2 A  t12 text11  
id2 A  t13 text12 

我想形成一個數據幀,甚至一個文本文件是這樣的:

id Role text      
id1 A  text1      
id1 B  text2, text3    
id1 A  text4      
id1 B  text5      
id1 A  text6, text7    
id2 A  text8      
id2 B  text9, text10, text11  
id2 A  text12, text13   
id2 B  text11     
id2 A  text12, text13   

或在文本格式:

text1 
text2, text3 
text4 
text5 
text6, text7 
==NEXT ID== 
text8 
text9, text10, text11 
text12, text13 
text11 
text12, text13 

我在熊貓使用GROUP BY,但我不能得到它,因爲按角色做就會把人文本一起。謝謝。

回答

4

檢查'Role'是否等於其先前值,並進行累計和以模擬第三個分組。

g3 = (df.Role != df.Role.shift()).cumsum().rename('clump') 
df.groupby(['id', 'Role', g3], sort=False).text.apply(', '.join).reset_index() 

    id Role clump     text 
0 id1 A  1     text1 
1 id1 B  2   text2, text3 
2 id1 A  3     text4 
3 id1 B  4     text5 
4 id1 A  5   text6, text7 
5 id2 A  5     text8 
6 id2 B  6 text9, text1, text10 
7 id2 A  7  text11, text12 

轉儲這個文本文件

g3 = (df.Role != df.Role.shift()).cumsum().rename('clump') 
d1 = df.groupby(['id', 'Role', g3], sort=False).text.apply(', '.join).reset_index() 

for n, g in d1.groupby('id').text: 
    print(g) 
    print() 
    # g.to_csv('{}.csv'.format(n)) 

0   text1 
1 text2, text3 
2   text4 
3   text5 
4 text6, text7 
Name: text, dtype: object 

5     text8 
6 text9, text1, text10 
7   text11, text12 
Name: text, dtype: object 
+0

謝謝@piRSquared我把它改爲'。適用(STR)'以避免'浮found'錯誤時該字符串是一個數字。如果我想通過遍歷每個'id'的行將其轉換爲文本,你推薦什麼? – Nick

+0

@Nick'astype(str)'更好。 – piRSquared

+0

謝謝。你如何建議迭代組創建一個文本文件? – Nick