Reputation: 1223
I have data frame df
that can be re-created with the code below:
df1 = pd.DataFrame({'name': ['jim', 'john', 'joe', 'jack', 'jake']})
df2 = pd.DataFrame({'name': ['jim', 'john', 'jack'],
'listings': [['orlando', 'los angeles', 'houston'],
['buffalo', 'boston', 'dallas', 'none'],
['phoenix', 'montreal', 'seattle', 'none']]})
df = pd.merge(df1, df2, on = 'name', how = 'left')
print(df)
name listings
0 jim [orlando, los angeles, houston, detroit]
1 john [buffalo, boston, dallas, none]
2 joe NaN
3 jack [phoenix, montreal, seattle, none]
4 jake NaN
I want to fill the NaN
values in the listings
column with a list of none
repeated the length of the the lists in the listings
column, ['none']*4
, so that the resulting dataframe looks like below:
print(df)
name listings
0 jim [orlando, los angeles, houston, detroit]
1 john [buffalo, boston, dallas, none]
2 joe [none, none, none, none]
3 jack [phoenix, montreal, seattle, none]
4 jake [none, none, none, none]
I've tried both approaches below, and neither are working:
# Failed Approach 1
df['listings'] = np.where(df['listings'].isnull(), ['none']*4, df['listings'])
# Failed Approach 2
df['listings'].fillna(['none']*4)
Upvotes: 2
Views: 61
Reputation: 75130
you can do:
df.loc[df['listings'].isna(),'listings'] = [['none']*4]
name listings
0 jim [orlando, los angeles, houston]
1 john [buffalo, boston, dallas, none]
2 joe [none, none, none, none]
3 jack [phoenix, montreal, seattle, none]
4 jake [none, none, none, none]
Upvotes: 4