简体   繁体   English

基于另一个多个数据框列的新列

[英]New column based on another multiple dataframe columns

Below is my dataframe.下面是我的数据框。

a一个 b b
12 12 0 0
1 1 21 21
0 0 0 0

Now want to add a column name 'c' which return yes when a or b is non-zero and return no when a and b is zero现在要添加一个列名“c”,当 a 或 b 为非零时返回 yes,当 a 和 b 为零时返回 no

a一个 b b c C
12 12 0 0 yes是的
1 1 21 21 yes是的
0 0 0 0 no

If need test all columns compare by 0 and test if all values per row by DataFrame.all with set yes , 'no' by numpy.where :如果需要测试所有列比较0并通过DataFrame.all测试每行的所有值是否设置yes , 'no' 通过numpy.where

df['c'] = np.where(df.eq(0).all(axis=1), 'no','yes')

print (df)
    a   b    c
0  12   0  yes
1   1  21  yes
2   0   0   no

Another idea is test if at leastone value is not 0 by DataFrame.any , then is used mapping:另一个想法是通过DataFrame.any测试是否至少一个值不为0 ,然后使用映射:

df['c'] = df.ne(0).any(axis=1).map({False: 'no',True:'yes'})

If possible multiple columns and need test only a,b columns:如果可能的话,多列并且只需要测试a,b列:

cols = ['a','b']
df['c'] = np.where(df[cols].eq(0).all(axis=1), 'no','yes')

Here is the simplest solution I can think of:这是我能想到的最简单的解决方案:

import numpy as np
df['c'] = np.where( (df['a']>0) | (df['b']>0), 'yes', 'no')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据时间标准将值从一个数据框中的多个列传输到另一个数据框中的新列 - Transferring values from multiple columns in a dataframe to a new column in another dataframe, based on time-criterion Pandas 根据另一个数据框中的匹配列填充新的数据框列 - Pandas populate new dataframe column based on matching columns in another dataframe DataFrame 中的新列基于来自另一个 DataFrame 的行和列 - New column in DataFrame based on rows and columns from another DataFrame 根据来自另一个数据帧的多列条件创建多列 - Create multiple columns based on multiple column conditions from another dataframe 基于来自另一个数据框的其他列创建新列 - Creating a new column based on other columns from another dataframe 插入几个新列,其值基于 pandas 中 Dataframe 中的另一列 - Insert several new column with the values based on another columns in a Dataframe in pandas 根据列和另一个字典中的索引列表创建新的 dataframe 列 - Create new dataframe columns based on lists of indices in a column and another dictionary 根据多列中的行值创建新的数据框列 - Creating a new dataframe column based on row values from multiple columns 根据多个列中的值创建新的数据框列 - Create new dataframe column based on values in multiple columns 根据多个其他列的条件新建 Python DataFrame 列 - Create new Python DataFrame column based on conditions of multiple other columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM