繁体   English   中英

如何在给定条件的情况下用 pandas dataframe 中的另一列替换一列的值

[英]How to replace the values of a column with another column in pandas dataframe given a condition

我有一个 pandas dataframe:

第 1 列 栏目 2
0 4个
2个 5个
0 2个
0 1个
5个 7
0 5个

我想用相应的 Col 2 值替换 Col 1 值。 但它应该仅在 Col 1 值 = 0 时才替换该值。一旦列值被替换,被替换的值应该为零。 基本上我想交换值。

所需的 output 应该是:

第 1 列 栏目 2
4个 0
2个 5个
2个 0
1个 0
5个 7
5个 0

请帮助代码。

使用boolean 索引

# identify rows to swap 
m = df['Col 1'].eq(0)

# swap values
df.loc[m, ['Col 1', 'Col 2']] = df.loc[m, ['Col 2', 'Col 1']].to_numpy()

更新 DataFrame:

   Col 1  Col 2
0      4      0
1      2      5
2      2      0
3      1      0
4      5      7
5      5      0
df['Col 1']=df.apply(lambda row: row['Col 2'] if row['Col 1']==0 else row['Col 1'],axis=1)
df
Out[255]: 
   Col 1  Col 2
0     4     4
1     2     5
2     2     2
3     1     1
4     5     7
5     5     5

您可以使用mask

# Columns to swap on condition
cols = ['Col 1', 'Col 2']
cond = df['Col 1'] == 0

df[cols] = df[cols].mask(cond, other=df[cols[::-1]].to_numpy())

Output:

第 1 列 栏目 2
4个 0
2个 5个
2个 0
1个 0
5个 7
5个 0

我们可以使用 Numpy where 在两列之间交换值。

# Importing Modules
import pandas as pd
import numpy as np

# Creating DataFrame
df = pd.DataFrame({'col1': [0, 2, 0, 0, 5, 0], 'col2':[4, 5, 2, 1, 7, 5]})

# Swaping values between two columns based on the condition
df['col1'],df['col2']=np.where(df['col1']==0,(df['col2'],df['col1']),(df['col1'],df['col2']))

最后 Output

   col1 col2
0   4   0
1   2   5
2   2   0
3   1   0
4   5   7
5   5   0

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM