关于其他行的值在pandas中创建一个新列 [英] Creating a new column in pandas with respect to the values of other rows
本文介绍了关于其他行的值在pandas中创建一个新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个示例数据:
column1 column2 column3 column4
0. 1. 1. 0
1. 1. 1. 1
0. 0. 0. 0
1. 1. 1. 0
1. 1. 1. 1
我想创建一个新的列(输出),如果数据帧的所有行值均为1,则显示1,否则为0.
I would like to create a new column(output) which shows 1 if all the row values of the dataframe are 1, otherwise 0.
示例输出如下所示:
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
推荐答案
您可以使用numpy select()
You can use the 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)
如果您有多列,则可以使用np.apply_along_axis()
if you have multiple columns you can use the 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)
这篇关于关于其他行的值在pandas中创建一个新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文