2024-04-20 05:45:03 发布
网友
我有一个数据帧df,有列'a'、'b'和'c'。我想创建列“d”,每行都有条件:
if type(a) != str: df['d'] = df['a'] else: df['d'] = df['b']/df['c']
“a”中的一些值是字符串,而另一些不是。你知道吗
您可以使用numpy.where
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的方法:
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)
您可以使用
numpy.where
下面是另一种使用
apply
的方法:相关问题 更多 >
编程相关推荐