[英]Creating a new column in pandas with respect to the values of other rows
I have a sample data as:我有一个示例数据:
column1 column2 column3 column4
0. 1. 1. 0
1. 1. 1. 1
0. 0. 0. 0
1. 1. 1. 0
1. 1. 1. 1
I would like to create a new column(output) which shows 1 if all the row values of the dataframe are 1, otherwise 0.我想创建一个新列(输出),如果 dataframe 的所有行值为 1,则显示 1,否则为 0。
The sample output is shown below:样品 output 如下所示:
column1 column2 column3 column4. output
0. 1. 1. 0. 0
1. 1. 1. 1. 1
0. 0. 0. 0. 0
1. 1. 1. 0. 0
1. 1. 1. 1. 1
You can use the numpy select()您可以使用 numpy select()
import pandas as pd
import numpy as np
condition = [(df.column1==1) & (df.column2==1) & (df.column3==1) & (df.column4==1)]
choices = [1]
df['output'] =np.select(condition, choices, default= 0)
if you have multiple columns you can use the np.apply_along_axis()如果您有多个列,则可以使用 np.apply_along_axis()
def ex(x):
a = 0
if x.all() == 1.0:
a = 1
return a
df['output'] = np.apply_along_axis(ex,1,df)
If there is only 0, 1
values use DataFrame.all
, because 0
is processing like False
and 1
like True
:如果只有0, 1
值使用DataFrame.all
,因为0
像False
一样处理而1
像True
:
df['new'] = df.all(axis=1).astype(int)
#alternative
#df['new'] = np.where(df.all(axis=1), 1, 0)
print (df)
column1 column2 column3 column4 new
0 0.0 1.0 1.0 0 0
1 1.0 1.0 1.0 1 1
2 0.0 0.0 0.0 0 0
3 1.0 1.0 1.0 0 0
4 1.0 1.0 1.0 1 1
If there are also another values compare by 1
:如果还有其他值比较1
:
df['new'] = df.eq(1).all(axis=1).astype(int)
If need choose only some columns:如果需要只选择一些列:
cols = ['column1', 'column2', 'column3', 'column4']
df['new'] = df[cols].eq(1).all(axis=1).astype(int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.