pandas apply changing dtype

Viewed 712

I'm trying to convert a pandas dataframe into a Series of tuples:

Example input:

df = pd.DataFrame([[1,2,3.0],[3,4,5.0]])

Desired Output:

0    (1, 2, 3.0)
1    (3, 4, 5.0)
dtype: object    

However pandas seems to coerce my integer columns to floats.

I tried

import pandas as pd

df = pd.DataFrame([[1,2,3.0],[3,4,5]])
print(df)
print(df.dtypes)
print(df.apply(tuple,axis=1,reduce=False).apply(str))

Actual output:

   0  1    2
0  1  2  3.0
1  3  4  5.0

0      int64
1      int64
2    float64
dtype: object

0    (1.0, 2.0, 3.0)
1    (3.0, 4.0, 5.0)
dtype: object

This question suggests using reduce=False but this doesn't change anything for me.

Could someone explain why pandas is coercing the datatype somewhere along the way?

2 Answers

pandas.DataFrame.itertuples

to avoid forcing your ints to floats

pd.Series([*df.itertuples(index=False)])

0    (1, 2, 3.0)
1    (3, 4, 5.0)
dtype: object

zip, map, splat... magic

pd.Series([*zip(*map(df.get, df))])

0    (1, 2, 3.0)
1    (3, 4, 5.0)
dtype: object

Adding python2.7 compatible solution:

In [3]: pd.Series(tuple(i) for i in df.itertuples())
Out[4]:
0    (0, 1, 2, 3.0)
1    (1, 3, 4, 5.0)
dtype: object
Related