Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

python - Why does apply change dtype in pandas dataframe columns

I have the following dataframe:

import pandas as pd
import numpy as np
df = pd.DataFrame(dict(A = np.arange(3), 
                         B = np.random.randn(3), 
                         C = ['foo','bar','bah'], 
                         D = pd.Timestamp('20130101')))

print(df)

   A         B    C          D
0  0 -1.087180  foo 2013-01-01
1  1 -1.343424  bar 2013-01-01
2  2 -0.193371  bah 2013-01-01

dtypes for columns:

print(df.dtypes)
A             int32
B           float64
C            object
D    datetime64[ns]
dtype: object

But after using apply they all changes to object:

print(df.apply(lambda x: x.dtype))
A    object
B    object
C    object
D    object
dtype: object

Why are dtypes coerced to object? I thought that in apply only columns should be taken in account.

pandas 0.17.1
python 3.4.3

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use parameter reduce=False and more info here:

print (df.apply(lambda x: x.dtype, reduce=False))

A             int32
B           float64
C            object
D    datetime64[ns]
dtype: object

In newer versions of pandas is possible use:

print (df.apply(lambda x: x.dtype, result_type='expand'))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...