簡體   English   中英

根據其他列的值將值分配給 dataframe 列的正確方法

[英]Correct way to assign values to a dataframe column based on the values of other columns

我有一個 dataframe 看起來像這樣:

   a     b      c
0  A   1.0   10.0
1  B   2.0   20.0
2  C   3.0   30.0
3  A   4.0   40.0
4  B   5.0   50.0
5  C   6.0   60.0
6  A   7.0   70.0
7  B   8.0   80.0
8  C   9.0   90.0
9  A  10.0  100.0

我想創建一個列'd',其值取決於'a',這樣如果列'a'的值在['A','B']中,那么列'd'獲取'b'中的值或否則它會得到'c'中的值。 我想要的結果是:

   a     b      c     d
0  A   1.0   10.0   1.0
1  B   2.0   20.0   2.0
2  C   3.0   30.0  30.0
3  A   4.0   40.0   4.0
4  B   5.0   50.0   5.0
5  C   6.0   60.0  60.0
6  A   7.0   70.0   7.0
7  B   8.0   80.0   8.0
8  C   9.0   90.0  90.0
9  A  10.0  100.0  10.0

我努力了:

df["d"] = np.nan

for i in range(df.shape[0]):
    if df.a.iloc[i] in ['A','B']:
        df.d.iloc[i] = df.b.iloc[i]
    elif df.a.iloc[i] in ['C']:
        df.d.iloc[i] = df.c.iloc[i]

這給了我想要的答案,但我收到錯誤消息“SettingWithCopyWarning:試圖在 DataFrame 的切片副本上設置一個值”

我也知道 for 循環並不理想,所以我嘗試使用 boolean 掩碼來執行此操作,但是

print(df.a in ['A','B'])

給我警告,“ValueError:一個系列的真值是不明確的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。”

a)修復for循環或b)用更優雅的東西替換for循環的最佳方法是什么? 我花了一個小時瀏覽 SO,但我找不到針對我的具體問題的好答案。 任何幫助表示贊賞。

您可以使用np.where

In [1696]: df['d'] = np.where(df['a'].isin(['A', 'B']), df['b'], df['c'])     
In [1697]: df 
Out[1697]: 
   a     b      c     d
0  A   1.0   10.0   1.0
1  B   2.0   20.0   2.0
2  C   3.0   30.0  30.0
3  A   4.0   40.0   4.0
4  B   5.0   50.0   5.0
5  C   6.0   60.0  60.0
6  A   7.0   70.0   7.0
7  B   8.0   80.0   8.0
8  C   9.0   90.0  90.0
9  A  10.0  100.0  10.0

您可以使用isinnp.select

df['d'] = np.select( (df.a.isin(['A','B']), df.a.eq('C')),
                    (df.b, df.c), np.nan)

如果a列僅由示例數據中所示的值A,B,C組成,您可以簡單地使用np.where

df['d'] = np.where(df.a.isin(['A','B']), df.b, df.c)

# or
# df['d'] = np.where(df.a.eq('C'), df.c, df.b)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM