简体   繁体   English

根据Pandas数据帧中其他列的值设置列的值

[英]Setting value of a column based on values of other columns in Pandas dataframe

I have this Pandas dataframe: 我有这个Pandas数据帧:

在此输入图像描述

This is some fictional data about games of cricket played between two countries. 这是两个国家之间关于板球比赛的一些虚构数据。 I want to set the value of column winner based on this simple logic: 我想根据这个简单的逻辑设置列获胜者的值:

if country_1_runs == country_2_runs:
    winner = 3
elif country_1_runs > country_2_runs:
    winner = 1
else:
    winner = 2

I know about map and apply methods in Pandas. 我知道Pandas中的地图和应用方法。 But I'm not certain if they allow conditional expressions like the above. 但我不确定他们是否允许像上面这样的条件表达式。

Use numpy.select : 使用numpy.select

m1 = df.country_1_runs == df.country_2_runs
m2 = df.country_1_runs > df.country_2_runs

df['winner'] = np.select([m1, m2], [3, 1], default=2)

You can try 你可以试试

df['winner'] = np.where(df['country_1_runs'] == df['country_2_runs'], 3, 
    np.where(df['country_1_runs']> df['country_2_runs'], 1, 2))

暂无
暂无

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

相关问题 根据 dataframe 中的其他列更改 pandas dataframe 列值 - Change pandas dataframe column values based on other columns in dataframe 根据其他列单元格的值设置熊猫DataFrame单元格的内容 - Setting the content of a pandas DataFrame cell based on the values of other columns cells Pandas dataframe select 列基于其他 Z6A8064B5DF479455500553 列中的值47DC - Pandas dataframe select Columns based on other dataframe contains column value in it 如何将基于其他列值的列附加到pandas数据框 - How to append columns based on other column values to pandas dataframe pandas dataframe根据相应行的其他列更新列值 - pandas dataframe update column values based on other columns of the corresponding row 根据 pandas dataframe 中的其他三列更改一列的值 - Changing values of one column based on the other three columns in pandas dataframe 根据其他列中的“NaN”值在 Pandas Dataframe 中创建一个新列 - Create a new column in Pandas Dataframe based on the 'NaN' values in other columns 在pandas数据框中,我想基于将其他列过滤为某些值来为该列分配值 - In a pandas dataframe I would like to assign a value to a column based on filtering other columns to certain values 根据同一pandas数据框中的其他列为列分配值 - Assign value to a column based of other columns from the same pandas dataframe 在pandas数据框列中选择值,对应于其他列中的值 - Selecting value in a pandas dataframe column, corresponding to values in other columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM