I need to conditionally set value of each row of a particular column in a dataframe. If the condition meets then the particular cell should be changed according to variable provided in the list, otherwise it should remain as it is. Please find below script hereunder. The current script set all values.
Many Thanks
import pandas as pd
df = pd.DataFrame({'Name': ['A', 'B', 'C', 'D'],
'Functions': [1000, 2000, 3000, 5000],
'value': [5, 6, 7, 8],
'Shape': ['Round', 'Round', 'Round', 'Round']})
x1 = 500
x2 = 700
x3 = 800
x4 = 900
x = [x1, x2, x3]
for index,row in df.iterrows():
if row['Functions'] <= 2200:
df.at[0, 'Functions']=x1
df.at[1, 'Functions']=x2
df.at[2, 'Functions']=x3
df.at[3, 'Functions']=x4
CodePudding user response:
If list has same length like number of rows in DataFrame is possible simplify solution with filtering list and values for set:
m = df['Functions'] <= 2200
df.loc[m, 'Functions']= np.array([x1, x2, x3, x4])[m]
print (df)
Name Functions value Shape
0 A 500 5 Round
1 B 700 6 Round
2 C 3000 7 Round
3 D 5000 8 Round
But if need set values by indices use:
m = df['Functions'] <= 2200
df.at[(df.index == 0) & m, 'Functions']=x1
df.at[(df.index == 1) & m, 'Functions']=x2
df.at[(df.index == 2) & m, 'Functions']=x3
df.at[(df.index == 3) & m, 'Functions']=x4
print (df)
Name Functions value Shape
0 A 500 5 Round
1 B 700 6 Round
2 C 3000 7 Round
3 D 5000 8 Round
CodePudding user response:
Maybe you can use numpy.where()
np.where(df['Functions']<=2200, x, df['Functions'])