Python:从其他列中选择的列中获取值

问题描述 投票:2回答:3

我有简单的DataFrame,如下所示:

df
   A   B    C err col
0  1  10  100   x   A
1  2  20  200   y   C
2  3  30  300   z   D
3  4  40  400   q   B

我想创建具有以下内容的df['result']

  1. col中指定的列的值
  2. err中的值,如果没有匹配项(如第2行中的D)
   A   B    C err col result
0  1  10  100   x   A      1
1  2  20  200   y   C    200
2  3  30  300   z   D      z
3  4  40  400   q   B     40
python pandas dataframe
3个回答
5
投票

使用Series.whereSeries.whereSeries.isin

首先,我们创建一个名为Series.isin的系列,它检查列名是否在DataFrame.lookup中,否则填充DataFrame.lookup

然后,我们使用temp查找col的标签并获取每行的值:

err
lookup

1
投票

您可以使用col逐行处理DataFrame。

在特定行上,可以使用语法temp = df['col'].where(df['col'].isin(df.columns), other='err') df['result'] = df.lookup(df.index, temp) 来获取特定列的值(如果存在),但是如果该列不存在,则默认使用第二个参数。

全部放在一起:

   A   B    C err col result
0  1  10  100   x   A      1
1  2  20  200   y   C    200
2  3  30  300   z   D      z
3  4  40  400   q   B     40

1
投票

您可以创建一个能够为您执行此操作的功能。

例如:

df.apply(..., axis=1)

然后您可以使用DataFrame.apply()将此函数应用于DataFrame中的每一行。

row.get(column, default)
© www.soinside.com 2019 - 2024. All rights reserved.