我创建了一个数据框,并以不同的方式调用 apply(type)/applymap(type) 。问题是我得到了不同的结果。我对 int
和 int64
类型感到困惑。
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 对象上。我的信念是apply
在 Series.apply
中隐式地执行类似的操作,以便将每行的值传递给 apply
的函数在本例中接收 ( type
,这就是为什么您看到 <class 'int'>
而不是 <class 'np.int64'>
。
关于python - 为什么 apply(type) 在 pandas 中得到不一致的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47988770/