I have following Datarame
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7],
'col_3': [14, 15, 16, 19]
})
I try to convert the numeric to string, and then combine each row into one string
I can achieve this by using :
df.apply(lambda x : ''.join(x.astype(str)),1)
Out[209]:
0 0414
1 1515
2 2616
3 3719
dtype: object# notice here dtype is object
This is the question
Then , I try to using sum
df.astype(str).sum(1)
Out[211]:
0 414.0
1 1515.0
2 2616.0
3 3719.0
dtype: float64
Notice here the dtype
become float
not object
.
Here is more information :
df.astype(str).applymap(type)
Out[221]:
col_1 col_2 col_3
0 <class 'str'> <class 'str'> <class 'str'>
1 <class 'str'> <class 'str'> <class 'str'>
2 <class 'str'> <class 'str'> <class 'str'>
3 <class 'str'> <class 'str'> <class 'str'>
Why sum
have this wired behavior? Is there any way to block it convert str
back to float
?
Thanks for your help :-)