【问题标题】:How to cast column of Unicode in data frame to integer?如何将数据框中的 Unicode 列转换为整数?
【发布时间】:2019-08-24 18:01:55
【问题描述】:

我有一个 pandas 数据框(名为 cmets),其中一列是时间戳(例如:2018-11-26),我将该列分成三个单独的列(年、月和日),但数据是仍然是Unicode。我正在尝试将每一列的数据放入一个数组中,然后将它们转换为整数。

我尝试了两种不同的代码,但出现错误: “只有整数、切片 (:)、省略号 (...)、numpy.newaxis (None) 和整数或布尔数组是有效的索引”

这是我的代码:

    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)”时,限制类型将是一个整数,但我不知道为什么它不适合数组。

【问题讨论】:

    标签: python arrays dataframe unicode series


    【解决方案1】:

    您不需要 for 循环,只需使用 astype

    你可以使用类似的东西:

    comments['day'] = comments['day'].astype('int32')

    您可能想推荐pandas.DataFrame.astype

    【讨论】:

      猜你喜欢
      • 2019-05-20
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 2014-07-06
      • 2020-01-28
      • 1970-01-01
      相关资源
      最近更新 更多