嗨,我有一個 DataFrame,其值如下
| ID| Value| comments |
| 1 | a | |
| 2 | b | |
| 3 | a;b;c| |
| 4 | b;c | |
| 5 | d;a;c| |
對于它們所在的所有行,我需要從值到注釋轉移到 a 和 b。這樣只有 a 和 b 之外的值將保留在資料中。
新的 df 看起來像這樣
| ID| Value| comments |
| 1 | | a |
| 2 | | b |
| 3 | c | a;b |
| 4 | c | b |
| 5 | d;c | a |
你能給我一個方向我應該在哪里尋找這個問題的答案
uj5u.com熱心網友回復:
分解您的Value列,然后將其標記到右列:
out = df.assign(Value=df['Value'].str.split(';')).explode('Value')
out['col'] = np.where(out['Value'].isin(['a', 'b']), 'comments', 'Value')
print(out)
# Intermediate output
ID Value comments col
0 1 a NaN comments
1 2 b NaN comments
2 3 a NaN comments
2 3 b NaN comments
2 3 c NaN Value
3 4 b NaN comments
3 4 c NaN Value
4 5 d NaN Value
4 5 a NaN comments
4 5 c NaN Value
現在旋轉您的資料框:
out = out.pivot_table(index='ID', columns='col', values='Value', aggfunc=';'.join) \
.fillna('').reset_index().rename_axis(columns=None)
print(out)
# Final output
ID Value comments
0 1 a
1 2 b
2 3 c a;b
3 4 c b
4 5 d;c a
uj5u.com熱心網友回復:
(i)str.split用于拆分';'和分解“值”列
(ii) 使用布爾索引來過濾存在'a'或'b'存在的行,將它們取出并groupby索引并';'作為分隔符連接它們
exploded_series = df['Value'].str.split(';').explode()
mask = exploded_series.isin(['a','b'])
df['comments'] = exploded_series[mask].groupby(level=0).apply(';'.join)
df['Value'] = exploded_series[~mask].groupby(level=0).apply(';'.join)
df = df.fillna('')
輸出:
ID Value comments
0 1 a
1 2 b
2 3 c a;b
3 4 c b
4 5 d;c a
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414815.html
標籤:
