![](/img/trans.png)
[英]Create a new column in pandas based on values in multiple columns and the same condition
[英]How can I iterate over column values in Pandas and create a new observation based on the values of multiple columns in the same row?
因此,發布了這個問題的許多變體,但它們都不是我正在尋找的。
我有一個數據集,其中包含多個包含 boolean 值的列,這些值指示用戶是否在其居住地列出了城市名稱。 用戶可以命名多個城市名稱。 見下文。
+----+----------+-------+-------------+------------------------------------+
| ID | New York | LA | New Orleans | New Var |
+----+----------+-------+-------------+------------------------------------+
| 1 | True | False | True | 'New York, NY', 'New Orleans, LA' |
| 2 | True | False | False | 'New York, NY |
| 3 | False | False | False | 'None' |
+----+----------+-------+-------------+------------------------------------+
我要做的是創建一個新列,用於存儲用戶列出的所有城市名稱的文本名稱。 我可以用一百萬個嵌套的 if 條件來做到這一點,但我確信在 Pandas 中有更好的方法來做到這一點。 誰能指出我正確的方向?
您可以將布爾值乘以字符串,並且由於 pandas 的 sum() function 連接字符串,您可以獲取數據和列值的點積。 兩者都做,你可以這樣做:
df = pd.DataFrame({'NY':[True, True, False],'SF':[True, False, True]})
delimiter = ", "
tmp= df.rename(columns=lambda x: x+delimiter)
df['Cities'] = tmp.dot(tmp.columns).str[:-len(delimiter)]
df
#~ NY SF Cities
#~ 0 True True NY, SF
#~ 1 True False NY
#~ 2 False True SF
如果只有一些列是城市名稱,您可以列出城市列並使用這些列:
cities = ['NY','SF']
tmp= df[cities].rename(columns=lambda x: x+delimiter)
IIUC,如果您的值確實是 True boolean 值,您可以使用np.where
或df.dot
import numpy as np
#to keep the peformance of numpy arrays i would suggest doing
#df.columns = df.columns.map(lambda x : f'{x},')
df['places'] = df.dot(df.columns)
New York LA New Orleans places
ID
1.0 True False True New YorkNew Orleans
2.0 True False False New York
3.0 False False False
或使用 numpy。
df['places_2'] = np.where(df, df.columns, '').sum(axis=1)
New York LA New Orleans places_2
ID
1.0 True False True New YorkNew Orleans
2.0 True False False New York
3.0 False False False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.