I have two columns with strings. I would like to combine them and ignore nan
values. Such that:
ColA, Colb, ColA+ColB str str strstr str nan str nan str str
I tried df['ColA+ColB'] = df['ColA'] + df['ColB']
but that creates a nan value if either column is nan. I've also thought about using concat
.
I suppose I could just go with that, and then use some df.ColA+ColB[df[ColA] = nan] = df[ColA]
but that seems like quite the workaround.
sum() Method to Find the Sum Ignoring NaN Values. Use the default value of the skipna parameter i.e. skipna=True to find the sum of DataFrame along the specified axis, ignoring NaN values. If you set skipna=True , you'll get NaN values of sums if the DataFrame has NaN values.
Use df. replace(np. nan,'',regex=True) method to replace all NaN values to an empty string in the Pandas DataFrame column.
By use + operator simply you can concatenate two or multiple text/string columns in pandas DataFrame.
Call fillna
and pass an empty str as the fill value and then sum
with param axis=1
:
In [3]: df = pd.DataFrame({'a':['asd',np.NaN,'asdsa'], 'b':['asdas','asdas',np.NaN]}) df Out[3]: a b 0 asd asdas 1 NaN asdas 2 asdsa NaN In [7]: df['a+b'] = df.fillna('').sum(axis=1) df Out[7]: a b a+b 0 asd asdas asdasdas 1 NaN asdas asdas 2 asdsa NaN asdsa
You could fill the NaN with an empty string:
df['ColA+ColB'] = df['ColA'].fillna('') + df['ColB'].fillna('')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With