我有以下資料框:
import pandas as pd
df = pd.DataFrame({'Date':['2022-01-01', '2022-01-01','2022-01-01','2022-02-01','2022-02-01',
'2022-03-01','2022-03-01','2022-03-01'],
'Type': ['R','R','R','P','P','G','G','G'],
'Class':[1,1,1,0,0,2,2,2],
'Text':['Hello-','I would like.','to be merged.','with all other.',
'sentences that.','belong to my same.','group.','thanks a lot.']})
df.index =[1,1,1,2,2,3,3,3]
我想做的是按索引分組以加入文本列,同時只保留其他列的第一行。
我嘗試了以下兩種解決方案,但均未成功。可能我應該將它們結合起來,但我不知道該怎么做。
# Approach 1
df.groupby([df.index],as_index=False).agg(lambda x : x.sum() if x.dtype=='float64' else ' '.join(x))
# Approach 2
df.groupby([df.index], as_index=False).agg({'Date': 'first',
'Type': 'first', 'Class': 'first', 'Test': 'join'})
結果應該是:
Date Type Class Text
2022-01-01 R 1 Hello. I would like to be merged.
2022-02-01 P 0 with all other sentences that.
2022-03-01 G 2 belong to my same. group. thanks a lot.
任何人都可以幫我做嗎?
謝謝!
uj5u.com熱心網友回復:
我的想法是采用第二種方法并將文本聚合到一個串列中,然后像這樣簡單地連接各個字串:
new_df = df.groupby([df.index], as_index=False).agg({'Date': 'first',
'Type': 'first', 'Class': 'first', 'Text': list})
new_df['Text'] = new_df['Text'].str.join('')
print(new_df)
輸出:
Date Type Class Text
0 2022-01-01 R 1 Hello-I would like.to be merged.
1 2022-02-01 P 0 with all other.sentences that.
2 2022-03-01 G 2 belong to my same.group.thanks a lot.
發現您也可以在單個陳述句中執行此操作(相同的方法):
new_df = df.groupby([df.index], as_index=False).agg({'Date': 'first',
'Type': 'first', 'Class': 'first', 'Text': ''.join})
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/424765.html
標籤:Python 熊猫 数据框 熊猫-groupby
上一篇:在資料框中以布林值獲取美國假期
下一篇:熊貓對另一列的布林值之間的行求和
