基于 if-else 条件和查找创建新的 pandas 数据框列

问题描述

我有一个 pandas 数据框,我需要根据 if-else 条件创建一个新列.这个问题已经在这里多次出现(例如,Creating基于 if-elif-else 条件的新列).

I have a pandas dataframe and I need to create a new column based on an if-else condition. This question already came up here multiple times (e.g., Creating a new column based on if-elif-else condition).

但是,我无法应用建议的解决方案,因为我还需要在列表中查找值以检查条件.我无法使用建议的解决方案执行此操作,因为我不确定如何在外部函数中访问我的查找列表.我的查找列表需要是全局的,我想避免这种情况.我觉得应该有更好的方法来做到这一点.

However, I cannot apply the proposed solution, since I also need to look up values in a list in order to check the condition. I cannot do this with the proposed solution, because I am not sure how I can access my lookup-list in the external function. My lookup-list would need to be global, which I want to avoid. I have the feeling there should be a better way to do this.

考虑以下数据框df:

letters
A
B
C
D
E
F

我还有一个包含查找值的列表:

I also have a list which contains lookup values:

lookup = [C,D]

现在,我想在我的数据框中创建一个新列,其中包含 1 如果相应的值包含在 lookup0 如果这些值不在 lookup 中.

Now, I want to create a new column in my dataframe which contains 1 if the respective value is contained in lookup and 0 if the values is not in lookup.

典型的方法是:

df.apply(helper, axis=1)

def helper(row):
  if(row['letters'].isin(lookup)):
     row['result'] = 1
  else:
     row['result'] = 0

但是,我不知道如何在 helper() 中访问 lookup 而不使其成为全局对象.

However, I do not know how I can access lookup in helper() without making it global.

结果应该是这样的:

letters    result
A          0
B          0
C          1
D          1
E          0
F          0


解决方案

虽然这个问题和问题很相似:如何在数据框的某些行的所有列上使用pandas应用函数

Although this question is very similar to the question: How to use pandas apply function on all columns of some rows of data frame

我认为这里值得展示几个方法,在一行中使用 np.where 和从 isinisin 将返回一个布尔系列,其中任何行都包含列表中的任何匹配项:

I think here it's worth showing a couple methods, on a single line using np.where with a boolean mask generated from isin, isin will return a boolean Series where any rows contain any matches in your list:

In [71]:
lookup = ['C','D']
df['result'] = np.where(df['letters'].isin(lookup), 1, 0)
df

Out[71]:
  letters  result
0       A       0
1       B       0
2       C       1
3       D       1
4       E       0
5       F       0

这里使用 2 个 loc 语句并使用 ~ 反转掩码:

here using 2 loc statements and using ~ to invert the mask:

In [72]:
df.loc[df['letters'].isin(lookup),'result'] = 1
df.loc[~df['letters'].isin(lookup),'result'] = 0
df

Out[72]:
  letters  result
0       A       0
1       B       0
2       C       1
3       D       1
4       E       0
5       F       0

相关文章