为什么在pandas数据框列中应用change dtype [英] Why does apply change dtype in pandas dataframe columns

查看:87
本文介绍了为什么在pandas数据框列中应用change dtype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

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用于列:

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

但是在使用 apply之后它们都更改为对象:

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

为什么dtypes强制对象?我认为在apply中只应考虑列.

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

推荐答案

您可以在此处在此处使用参数reduce=False和更多信息:

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'))

这篇关于为什么在pandas数据框列中应用change dtype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆