【发布时间】:2016-10-19 20:08:37
【问题描述】:
我有一个包含两列的数据框:一列是字符串,另一列是整数。正如预期的那样,整数列的数据类型是int64。但是,对于字符串列,它是object。
现在我想通过为每个字符串分配一个给定的整数来将字符串列转换为整数列。我这样做如下:
from pandas import DataFrame
# Create a data frame with two columns:
# - `catCol' represents categorical data and consists of strings
# - `intCol' represents numerical data and consists of integers
myList = {'catCol': ['NM', 'VT', 'VA', 'NY', 'VA'], 'intCol': [3, 6, 10, -1, 0]}
df = DataFrame(myList)
print('Before the mapping:')
print(df)
print('Data type of `catCol`:', df['catCol'].dtype)
print('Data type of a `catCol` element:', type(df['catCol'][3]))
print('Data type of `intCol`:', df['intCol'].dtype)
print('Data type of a `intCol` elements:', type(df['intCol'][3]))
# Replace the categorical columns with unique integers IDs.
fromList = df['catCol'].unique()
toList = list(range(len(fromList)))
for idx in range(len(fromList)):
df.loc[df['catCol'] == fromList[idx], 'catCol'] = toList[idx]
print()
print('After the mapping:')
print(df)
print('Data type of `catCol`:', df['catCol'].dtype)
print('Data type of a `catCol` element:', type(df['catCol'][3]))
print('Data type of `intCol`:', df['intCol'].dtype)
print('Data type of a `intCol` elements:', type(df['intCol'][3]))
输出是:
Before the mapping:
catCol intCol
0 NM 3
1 VT 6
2 VA 10
3 NY -1
4 VA 0
Data type of `catCol`: object
Data type of a `catCol` element: <class 'str'>
Data type of `intCol`: int64
Data type of a `intCol` elements: <class 'numpy.int64'>
After the mapping:
catCol intCol
0 0 3
1 1 6
2 2 10
3 3 -1
4 2 0
Data type of `catCol`: object
Data type of a `catCol` element: <class 'int'>
Data type of `intCol`: int64
Data type of a `intCol` elements: <class 'numpy.int64'>
问题来了:如果转换后的catCol 现在只包含整数,为什么它仍然是对象数据类型?我需要它是一个整数数据类型,就像intCol。我怎样才能解决这个不使用任何演员?
【问题讨论】:
-
@IgnacioVazquez-Abrams,实际上
object类型在 numpy/pandas 中表示字符串或数字和 NaN(非数字)值的混合
标签: python object pandas type-conversion