Home > Back-end >  Python, panda replace value using loc
Python, panda replace value using loc

Time:06-08

I don't understendt why this dose not work. I want to find all empty cells and write in it column name add 100. For exlample 'OrgName100'

columns =['OrgName','IdCode','CategoryMain']
for columnName in columns: 
       df.loc[df[columnName] == ' ', [columnName]] = columnName   '100'

CodePudding user response:

Replace your ' ' strings by nan then use fillna:

columns = ['OrgName', 'IdCode', 'CategoryMain']
mapping = {c: f'{c}100' for c in columns}
df[columns] = df[columns].replace(' ', np.nan).fillna(mapping)

Update

Instead of 100 can I add one columns certain row value. For example in OrgName in row5 is written "134", I want in Idcode row5 (in empty cell) to write Idcode134?

df1 = (pd.DataFrame([df.columns], columns=df.columns, index=df.index)
             df['OrgName'].values.reshape(-1, 1))
df[columns] = df[columns].replace(' ', np.nan).fillna(df1)
print(df)

# Output
  OrgName   IdCode CategoryMain
0       x        1            f
1       y        2            d
2       z  IdCodez            g
  • Related