Home > Enterprise >  How to complete a column with a condition on a dataframe?
How to complete a column with a condition on a dataframe?

Time:02-01

I'd like to start from this dataframe:

A B
a
a
c
e
f

to get this one :

A  B
a FIRST
a FIRST
c THIRD
e FIFTH
f SIXTH

I coded this but seems to consider only the last condition :

for i in range(len(df['A'])):
    if(df['A'][i] == 'a'):
                df['B'] = 'FIRST'
    if(df['A'][i] == 'c'):
                df['B'] = 'THIRD' 
    if(df['A'][i] == 'e'):
                df['B'] = 'FIFTH'
    if(df['A'][i] == 'f'):
                df['B'] = 'SIXTH'   

but seems to consider only the last condition...

CodePudding user response:

You can use pandas.Series.map.

>>> letter_to_word = {
...     "a": "FIRST",
...     "c": "THIRD",
...     "e": "FIFTH",
...     "f": "SIXTH"
... }
>>> 
>>> import pandas as pd
>>> 
>>> df = pd.DataFrame({
...     "A": ["a", "a", "c", "e", "f"]
... })
>>> 
>>> df["B"] = df["A"].map(letter_to_word)
>>> print(df)
   A      B
0  a  FIRST
1  a  FIRST
2  c  THIRD
3  e  FIFTH
4  f  SIXTH

CodePudding user response:

you're replacing df['B'] each time,

update your code as follows:

for i in range(len(df['A'])):
    if(df['A'][i] == 'a'):
                df['B'][i] = 'FIRST'
    elif(df['A'][i] == 'c'):
                df['B'][i] = 'THIRD' 
    elif(df['A'][i] == 'e'):
                df['B'][i] = 'FIFTH'
    elif(df['A'][i] == 'f'):
                df['B'][i] = 'SIXTH'   

changing df['B'] to df['B'][i] ensures you avoid overwriting the whole column each time.

output:

   A      B
0  a  FIRST
1  a  FIRST
2  c  THIRD
3  e  FIFTH
4  f  SIXTH

CodePudding user response:

I have shared the updated version of your code. it's working fine.

you were updating df['B'] each time.

for i in range(len(df['A'])):
    if(df['A'][i] == 'a'):
        df.at[i, 'B'] = 'FIRST'
    if(df['A'][i] == 'c'):
        df.at[i, 'B'] = 'THIRD' 
    if(df['A'][i] == 'e'):
        df.at[i, 'B'] = 'FIFTH'
    if(df['A'][i] == 'f'):
        df.at[i, 'B'] = 'SIXTH' 
  • Related