[英]Create pandas column based on condition of another column
這個表達
df["column"].diff() != 0
給我一個大熊貓系列的布爾。 我現在想要一個列df["result"]
,其中df["column"]
每個True值的值為100
,每個False的0
。
我不明白為什么這不起作用:
df["result"] = 100 if df["column"].diff() != 0 else 0
我知道我必須使用loc,但是從這個:
df.loc[df["column"].diff() != 0]
如何設置結果列?
這里最好使用numpy.where
按條件設置2值,解決方案是矢量化的:
df["result"] = np.where(df["column"].diff() != 0, 100, 0)
你的代碼:
df["result"] = 100 if df["column"].diff() != 0 else 0
不工作,因為這里使用1d數組,(系列)所以不能使用標量解決方案。
你還得到:
ValueError:Series的真值是不明確的。 使用a.empty,a.bool(),a.item(),a.any()或a.all()。
並且它意味着沒有明確的,來自df["column"].diff() != 0
的布爾數組的標量輸出是什么df["column"].diff() != 0
。
有關pandas使用if / truth語句的更多信息
可能你正在尋找這樣的東西:
df.loc[df['column'].diff()!=0, 'Result'] = 100
在jezrael的評論后編輯:
df['diff'] = df['column'].diff().fillna(0)
df.loc[df['diff'] != 0, 'Result'] = 100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.