我在熊貓中有一個資料框,如下所述,其中列中的元素與列info中的唯一檔案相同id:
id text info
1 great boy,police
1 excellent boy,police
2 nice girl,mother,teacher
2 good girl,mother,teacher
2 bad girl,mother,teacher
3 awesome grandmother
4 superb grandson
我只想將串列元素作為每個檔案的行,例如:
id text info
1 great boy
1 excellent police
2 nice girl
2 good mother
2 bad teacher
3 awesome grandmother
4 superb grandson
uj5u.com熱心網友回復:
一種使用pandas.DataFrame.groupby.transform.
請注意,這假設:
- 中的元素的
info長度與id分割后的每個成員的數量相同',' info相同 id 中的元素是相同的。
df["info"] = df.groupby("id")["info"].transform(lambda x: x.str.split(",").iloc[0])
print(df)
輸出:
id text info
0 1 great boy
1 1 excellent police
2 2 nice girl
3 2 good mother
4 2 bad teacher
5 3 awesome grandmother
6 4 superb grandson
uj5u.com熱心網友回復:
創建計算每組行數的臨時變數 info:
temp = df.groupby('info').cumcount()
做一個串列理解來索引每個文本info:
df['info'] = [ent.split(',')[pos] for ent, pos in zip(df['info'], temp)]
df
id text info
0 1 great boy
1 1 excellent police
2 2 nice girl
3 2 good mother
4 2 bad teacher
5 3 awesome grandmother
6 4 superb grandson
uj5u.com熱心網友回復:
或嘗試apply:
df['info'] = pd.DataFrame({'info': df['info'].str.split(','), 'n': df.groupby('id').cumcount()}).apply(lambda x: x['info'][x['n']], axis=1)
輸出:
>>> df
id text info
0 1 great boy
1 1 excellent police
2 2 nice girl
3 2 good mother
4 2 bad teacher
5 3 awesome grandmother
6 4 superb grandson
>>>
uj5u.com熱心網友回復:
讓我們試試
df['new'] = df.loc[~df.id.duplicated(),'info'].str.split(',').explode().values
df
id text info new
0 1 great boy,police boy
1 1 excellent boy,police police
2 2 nice girl,mother,teacher girl
3 2 good girl,mother,teacher mother
4 2 bad girl,mother,teacher teacher
5 3 awesome grandmother grandmother
6 4 superb grandson grandson
uj5u.com熱心網友回復:
利用'info'重復的事實。
df['info'] = df['info'].drop_duplicates().str.split(',').explode().to_numpy()
輸出:
id text info
0 1 great boy
1 1 excellent police
2 2 nice girl
3 2 good mother
4 2 bad teacher
5 3 awesome grandmother
6 4 superb grandson
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/381270.html
