![](/img/trans.png)
[英]how to replace the values of a column from another column with condition pandas python
[英]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']))
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.