Python 数据框:创建有条件地连接来自 1 或 3 个其他列的字符串值的新列

Python Data frame: Create New Column that Conditionally Concatenates String Values from 1 or 3 Other Columns

目标:创建根据原始列中的值输出字符串的新列

下面是我的数据框table。我想创建以黄色突出显示的新列。

以下是我的业务逻辑:

1. If value in 'Cat_Priority_1' = 'Cat_1' then the new column ('Cat_Priority_1_Rationale') is equal to the string values in 'Age_Flag', 'Salary_Flag', and 'Education_Flag' columns.  
2. If value in 'Cat_Priority_1' = 'Cat_3' then the new column ('Cat_Priority_1_Rationale') is equal to the string values in 'Race_Flag'

这是我试过的代码,但没有用:

非常感谢任何帮助!

apply 函数用于迭代数据框的列。

df = pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']})
df['period'] = df[['Year', 'quarter']].apply(lambda x: ''.join(x), axis=1)

给出这个数据框

  Year   quarter  period
0  2014      q1  2014q1
1  2015      q2  2015q2

或者您可以将每一行发送到一个单独的函数来处理 if 条件和 returns 连接的字符串。

这就是您可以直接实现业务逻辑的方式。

>>> def bus_log(row):
...     if row['Cat_Priority_1'] == 'Cat_1':
...         result = []
...         result.append(row['Age_Flag'])
...         result.append(row['Salary_Flag'])
...         result.append(row['Education_Flag'])
...         result = ';'.join(result)
...         if result.startswith(';'):
...             result = result[1:]
...         return result
...     elif row['Cat_Priority_1'] == 'Cat_3':
...         return row['Race_Flag']
...     elif ....: ## another condition could go here
...         ## calculate a result
...         return result
...     elif ....: ## another condition could go here
...         ## calculate a result
...         return result
...     else:
...         return ''
... 
>>> df['Cat_Priority_1_Rationale'] = df.apply(bus_log, axis=1)

有两点我应该提一下:(1) 在执行此操作之前,您应该从数据中清除 NaN 实例以支持空字符串。 (2) 我怀疑你数据的第三行有错误,在 'Salary_Flag' 值中。

你可以使用这样的东西。广播通常比遍历行更快、更易读。最后一行利用了 False * s == ''True * s == s 对于任何字符串 s.

这一事实
bs = df.Cat_priority_1 == 'Cat_1'
s1 = df.Race_Flag
s3 = df.Age_Flag + ';' + df.Educ_Flag + ';' + df.Salary_Flag
df['new_col'] = bs * s1 + (1 - bs) * s2

您可以使用 np.where 并使用 pd.np.where 通过 pandas 库访问它,它的作用类似于 if 语句:

df['Cat_Priority_1_Rationale']  = pd.np.where(df['Cat_Priority_1'] == 'Cat_1',
                                           df['Age_Flag'] + ";" + df['Salary_Flag'] + ";" + df['Education_Flag'],
                                           df['Race_Flag'])