繁体   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