Reputation: 979
I am merging two columns in pandas but getting a problem with "None".
my df:
id name1 name2
1 sam None
2 None slic
3 brm dres
I am using the concatenation method to combine name1 and name2
df['New'] df['name1] + df['name2']
but when i use this then all the values with None neglected... I don't know why. This is my output looks in the end
id name1 name2 New
3 brm dres brmdres
but i need this:
id name1 name2 New
1 sam None sam
2 None slic slic
3 brm dres brmdres
Upvotes: 1
Views: 63
Reputation: 171
Just a complete answer in the case where you only need to sum specific columns in the dataframe:
df = pd.DataFrame({'name1': ['sam', None, 'brm'],
'name2': [None, 'slic', 'dres'],
'name3': ['sam2', 'slic2', 'dres2']})
df['new'] = df['name1'].fillna('') + df['name2'].fillna('')
Just to explain what is happening: the fillna('') is replacing the None's with an empty string '' in a copy of the column. This means you are actually adding 'sam' to the empty string '' which gives you 'sam' again.
Upvotes: 1
Reputation: 323226
Try filter with replace
if the None
is string
type
, if not do fillna('')
df.filter(like='name').replace('None','').sum(1)
0 sam
1 slic
2 brmdres
dtype: object
Upvotes: 1