Home > Mobile >  Python: How to merge/join values from 2 columns in dataframe
Python: How to merge/join values from 2 columns in dataframe

Time:02-02

I've been searching around for a while now, but I can't seem to find the answer to this small problem.

I want to enter the contents of the value in the map column into the address column, so that the null value in the address column is filled with the value in the map column.

data_bio_dewasa = {'nama':['Sandy','Toni','Jami','Juda', 'Wong'],
            'age':[21, 32, 43, 26, 28],
            'address':[np.nan, 'tanjung duren', np.nan, 'kokas', np.nan],
            'food':['pizza','burger','bakso','mie ayam','seblak'],
            'edukasi':['s1','s2','d3','sma','s3'],
            'status':['pacaran','single','menikah','pelajar','mahasiswa'],
            'map':['banten',np.nan,'medan',np.nan,'kalimantan']
           }

df_bio_dewasa = pd.DataFrame(data_bio_dewasa)
df_bio_dewasa

Expected output for me should be: (the address column which was originally empty/nan will be filled with the values in the map column)

    nama    age   address          food     edukasi   status       map
0   Sandy   21    banten           pizza      s1      pacaran     banten
1   Toni    32   tanjung duren    burger      s2      single       NaN
2   Jami    43     medan           bakso      d3      menikah      medan
3   Juda    26     kokas          mie ayam    sma     pelajar      NaN
4   Wong    28    kalimantan       seblak     s3      mahasiswa   kalimantan

how to program to produce output like that?

CodePudding user response:

Simply fillna your "address" column with the "map" column:

df_bio_dewasa['address'] = df_bio_dewasa['address'].fillna(df_bio_dewasa['map'])

output:

    nama  age        address      food edukasi     status         map
0  Sandy   21         banten     pizza      s1    pacaran      banten
1   Toni   32  tanjung duren    burger      s2     single         NaN
2   Jami   43          medan     bakso      d3    menikah       medan
3   Juda   26          kokas  mie ayam     sma    pelajar         NaN
4   Wong   28     kalimantan    seblak      s3  mahasiswa  kalimantan

CodePudding user response:

Just use .fillna()

df_bio_dewasa['address'] = df_bio_dewasa['address'].fillna(df_bio_dewasa['map'])

Gives:

    nama  age        address      food edukasi     status         map
0  Sandy   21         banten     pizza      s1    pacaran      banten
1   Toni   32  tanjung duren    burger      s2     single         NaN
2   Jami   43          medan     bakso      d3    menikah       medan
3   Juda   26          kokas  mie ayam     sma    pelajar         NaN
4   Wong   28     kalimantan    seblak      s3  mahasiswa  kalimantan
  •  Tags:  
  • Related