python - 为什么 apply(type) 在 pandas 中得到不一致的结果?

标签 python pandas numpy

我创建了一个数据框,并以不同的方式调用 apply(type)/applymap(type) 。问题是我得到了不同的结果。我对 intint64 类型感到困惑。

In [116]: df_term[0:5]
Out[116]: 
                    term    tag  count  weight          pt
0                    -03  OTHER    380  3085.0  2017-12-06
1                   -300    NUM   1224  6120.0  2017-12-06
2                   -805  OTHER     30   258.0  2017-12-06
3  0-150mm0-200mm0-300mm     XH     27  1650.0  2017-12-06
4                 040639  OTHER     52   464.0  2017-12-06

In [106]: df_term.dtypes
Out[106]: 
term       object
tag        object
count       int64
weight    float64
pt         object
dtype: object

In [109]: type(df_term.iloc[0]['count'])
Out[109]: numpy.int64

In [111]: df_term.iloc[0].apply(type)['count']
Out[111]: numpy.int64

In [113]: type(df_term['count'].iloc[0])
Out[113]: numpy.int64

In [114]: df_term['count'].apply(type)[0]
Out[114]: int

In [115]: df_term[0:1].applymap(type)['count']
Out[115]: 
0    <type 'int'>
Name: count, dtype: object

我还尝试比较它们的类型:

In [156]: df_term.iloc[0].apply(type)['count']
Out[156]: numpy.int64

In [157]: df_term.applymap(type).iloc[0]['count']
Out[157]: int

In [158]: df_term.iloc[0].apply(type)['count'] == df_term.applymap(type).iloc[0]['count']
Out[158]: False

最佳答案

考虑一个简单的例子 -

In [13]: x = 5

In [14]: type(x)
Out[14]: int

In [15]: repr(type(x))
Out[15]: "<class 'int'>"

第一个输出是 IPython 对 type 的美化。返回。第二个输出是 __repr__相同的输出,这就是 pandas 向您展示的内容。

本质上,它们是同一件事。您可以看到IPython通过从 IPython.lib 显式导入它来运行 pretty-print -

s = pd.Series([1, 2, 3, 4])
s.apply(type)

0    <class 'int'>
1    <class 'int'>
2    <class 'int'>
3    <class 'int'>
dtype: object
from IPython.lib.pretty import pretty

for r in s.apply(type):
     print(pretty(r))

int
int
int
int 
<小时/>

关于int之间的区别和np.int64正在显示,请考虑 -

In [16]: df.loc[0, 'count']
Out[16]: 380

In [17]: type(df.loc[0, 'count'])
Out[17]: numpy.int64

In [18]: type(df.loc[0, 'count'].item())
Out[18]: int

默认情况下,数据加载到数据框列中 np对象。通过索引访问特定元素将始终返回 numpy 对象,然后您可以通过调用 .item() 将其转换为 python 对象。在 numpy 对象上。我的信念是applySeries.apply 中隐式地执行类似的操作,以便将每行的值传递给 apply 的函数在本例中接收 ( type ,这就是为什么您看到 <class 'int'> 而不是 <class 'np.int64'>

关于python - 为什么 apply(type) 在 pandas 中得到不一致的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47988770/

相关文章:

python - 使用 Pandas 根据该行中的值从 csv 文件中删除特定行之前的行

python - 需要从 python 列表理解中提取多个值?

python - 具有容差的两个数据集的最长公共(public)子序列

python - numpy 从数组下选择所有元素

python - django:管理小部件CSS?

python - 使用Regex Python提取特殊字符之间的字符

python - 使用 pandas 访问 CSV 文件中方括号内的数字?

python - 使用索引作为键从数据框创建字典

python - 合并 pandas 中的 2 个数据框

python - 使用编码为字符串的类别列表的 Pandas 假人