简体   繁体   中英

Pandas: How to replace values in a column using for loop if conditions are met

I'm having trouble changing values in a column using for loops if certain conditions are met.

Just a simple example, let's a we have a column of numbers, and I want to replace all numbers less than a 5 into some string like "Hello". How can I do this? I saw .iterrows() and and .set_value() but I'm not sure how to exactly code the for loop-if statement.

This is for Python/pandas

I assume you are using pandas as per the title.

import pandas as pd

df_series = pd.Series(data=[4, 1, -5, 6, 6, 7, 9, 8, 4, -5], index=range(10), name='Column1')
df_series[df_series < 5] = 'Hello'

Note: mixed types are not recommended in columns. The above code will change the type of the column from 'int64' to 'object'.

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