Search code examples
pythonpandasnanseriesmissing-data

How can I add a new column filled with values to a pandas DataFrame without getting NaN values?


I new to Python , I am trying to add new column filled with values but when run the code it shows NaN .

enter image description here

df0 = pd.DataFrame ({ 'GOV': [ 'Iraq' , 'Pakistan' , 'UAE' , 'UK' ] , 'CAPITAL' : [ 'Baghdad' , 'Islamabad' , 'DUBAI' , 'LONDON' ], 'POPULATION' : [100 , 300 , 120 , 150]
}, columns = ['GOV' , 'CAPITAL' , 'POPULATION'])

df0.index = ['A' , 'B' , 'C' , 'D']

lang = pd.Series(['Arabic', 'Urdu' , 'Arabic' , 'English'] ,index = ['Iraq' , 'Pakistan' , 'UAE' , 'UK'] , name = 'language'
)

df0['language'] = lang

Solution

  • You have set the index of lang which does not match with the index of df0.

    Instead, use pd.merge:

    df0 = pd.merge(df0, lang, left_on="GOV", right_index=True)