如何将数据框中的 Unicode 列转换为整数?
How to cast column of Unicode in data frame to integer?
我有一个 pandas 数据框(名为评论),其中一列是时间戳(例如:2018-11-26),我将该列拆分为三个单独的列(年、月和天),但数据仍然是 Unicode。我正在尝试将每一列的数据放入一个数组,然后将它们转换为整数。
我尝试了两种不同的代码,但出现错误:
"only integers, slices (:
), ellipsis (...
), numpy.newaxis (None
) and integer or boolean arrays are valid indices"
这是我的代码:
day_array=comments['day'].values
mounth_array=comments['mounth'].values
year_array=comments['year'].values
#My first try:
for i in day_array:
day_array[i] = int(day_array[i])
#My second try instead of first one:
for i in day_array:
hi=day_array[i]
limit = int(hi)
limit[i]=limit
我知道当我 运行 这个:"limit = int(hi)",限制类型将是一个整数,但我不知道为什么它不适合数组。
你不需要为此使用 for 循环,只需使用 astype.
您可以使用类似的东西:
comments['day'] = comments['day'].astype('int32')
您可能需要参考 pandas.DataFrame.astype。
我有一个 pandas 数据框(名为评论),其中一列是时间戳(例如:2018-11-26),我将该列拆分为三个单独的列(年、月和天),但数据仍然是 Unicode。我正在尝试将每一列的数据放入一个数组,然后将它们转换为整数。
我尝试了两种不同的代码,但出现错误:
"only integers, slices (:
), ellipsis (...
), numpy.newaxis (None
) and integer or boolean arrays are valid indices"
这是我的代码:
day_array=comments['day'].values
mounth_array=comments['mounth'].values
year_array=comments['year'].values
#My first try:
for i in day_array:
day_array[i] = int(day_array[i])
#My second try instead of first one:
for i in day_array:
hi=day_array[i]
limit = int(hi)
limit[i]=limit
我知道当我 运行 这个:"limit = int(hi)",限制类型将是一个整数,但我不知道为什么它不适合数组。
你不需要为此使用 for 循环,只需使用 astype.
您可以使用类似的东西:
comments['day'] = comments['day'].astype('int32')
您可能需要参考 pandas.DataFrame.astype。