如何根据布尔表达式和其他两列的关系在数据框中创建列

2024-04-20 05:45:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧df,有列'a'、'b'和'c'。我想创建列“d”,每行都有条件:

if type(a) != str:
    df['d'] = df['a']
else:
    df['d'] = df['b']/df['c']

“a”中的一些值是字符串,而另一些不是。你知道吗


Tags: 数据字符串dfiftype条件elsestr
1条回答
网友
1楼 · 发布于 2024-04-20 05:45:03

您可以使用numpy.where

a_is_str = df['a'].apply(lambda x: s is not str)


df['d'] = np.where(a_is_str, df['a'], df['b']/df['c'])

下面是另一种使用apply的方法:

def check_if_str(row):
    if isinstance(row['a'], str):
        return row['a']
    return row['b'] / row['c']

df['d'] = df.apply(check_if_str, axis=1)

相关问题 更多 >