简体   繁体   中英

Is there any way to replace values with different values in the same row if they meet a certain condition using a for loop?

I need to replace the values of a certain cell with values from another cell if a certain condition is met.

for r in df: 
    if df['col1'] > 1 :
        df['col2'] 
    else:

I am hoping for every value in column 1 to be replaced with their respective value in column 2 if the condition if the value of the row in column 1 is greater than 1.

No need to loop through the entire dataframe.

idx=df['col1']>1
df.loc[idx,'col1']=df.loc[idx,'col2']

Using a for loop

for _,row in df.iterrows():
    if row['col1']>1:
        row['col1']=row['col2']
    elif condition:
        #put assignment here
    else other_condition:
        #put assignment here

Here is an example

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 4, 6]})

print(df)
print('----------')

# the condition here is A^2 == B
df.loc[df['A'] * df['A'] == df['B'], 'A'] = df['B']

print(df)

output

   A  B
0  1  4
1  2  4
2  3  6
----------
   A  B
0  1  4
1  4  4
2  3  6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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