简体   繁体   中英

Python, panda replace value using loc

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'

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

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