Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas change values from a condition

how are you? I'm pretty new at code, and I have this question:

I want to iterate through a column, and I want to change this column values based on a condition, in this case, I want to change very value from column 'a1': if the value contains the word 'Juancito' I want to change it to just 'Juancito'. The for loop works OK, but the value doesn't change in the end.

What I'm doing wrong?

import pandas as pd
inp = [{'a1':'Juancito 1'}, {'a1':'Juancito 2'}, {'a1':'Juancito 3'}]
df = pd.DataFrame(inp)

for i in df['a1']:
    if 'Juancito' in i:
        i = 'Juancito'
    else:
        pass
df.head()
like image 214
Lucio Stortoni Ruiz Avatar asked May 13 '26 22:05

Lucio Stortoni Ruiz


1 Answers

You don't need a for loop.

Just use numpy.where with Series.str.contains:

In [83]: import numpy as np

In [84]: df['a1'] = np.where(df['a1'].str.contains('Juancito'), 'Juancito', df['a1'])

In [85]: df
Out[85]: 
         a1
0  Juancito
1  Juancito
2  Juancito
like image 132
Mayank Porwal Avatar answered May 16 '26 12:05

Mayank Porwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!