我创建了一个数据帧,并以不同的方式调用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__
,也是熊猫向您展示的内容。
从本质上讲,它们都是一回事。您可以通过从IPython.lib
显式导入来查看IPython
漂亮的打印机的运行情况 -
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 对象,然后您可以通过在 numpy 对象上调用.item()
将其转换为 python 对象。我的信念是apply
Series.apply
内隐式地做这样的事情,以便将每一行的值传递给apply
接收的函数(在这种情况下type
,这就是为什么你看到的是<class 'int'>
而不是<class 'np.int64'>
。