我有以下資料框:
| ID | 宣告_1 | 宣告_2 | 宣告_3 |
|---|---|---|---|
| xyz | 0.0 | 1.0 | 0.0 |
| 美國廣播公司 | 1.0 | 0.0 | 0.0 |
| 電子煙 | 0.0 | 0.0 | 1.0 |
我想根據條件創建一個新列,如果一行有 1.0,它回傳與之關聯的列名。
更清楚地說,我想要這個資料框作為回報:
| ID | 宣告_1 | 宣告_2 | 宣告_3 | 健康)狀況 |
|---|---|---|---|---|
| xyz | 0.0 | 1.0 | 0.0 | 宣告_2 |
| 美國廣播公司 | 1.0 | 0.0 | 0.0 | 宣告_1 |
| 電子煙 | 0.0 | 0.0 | 1.0 | 宣告_3 |
感謝所有可以幫助我的人!
uj5u.com熱心網友回復:
idxmax如果您確定每行至少有 1 個,請使用:
df['Condition'] = df.filter(like='Statement').idxmax(axis=1)
print(df)
# Output
id Statement_1 Statement_2 Statement_3 Condition
0 xyz 0.0 1.0 0.0 Statement_2
1 abc 1.0 0.0 0.0 Statement_1
2 efg 0.0 0.0 1.0 Statement_3
對于行中有 0、1 或更多 1 的情況,一種更穩健的方法:
df['Condition'] = df.filter(like='Statement').melt(ignore_index=False) \
.query('value == 1').groupby(level=0)['variable'] \
.apply(', '.join)
uj5u.com熱心網友回復:
如果可能,多個1值使用矩陣乘法
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/450771.html
上一篇:用逗號分割字串,同時保留數字部分
