【问题标题】:Changing datatype of pandas array from obj to int将 pandas 数组的数据类型从 obj 更改为 int
【发布时间】:2020-12-31 11:27:15
【问题描述】:

我在 pandas 中有一个 dtype 'object' 的数组,这个数组只包含整数,但由于错误,我无法将其转换为 int32 或任何与 Keras 兼容的数据类型:

ValueError: setting an array element with a sequence.

同时使用以下代码:

df['label'].astype('int64')

这是专栏:

0        [90, 90, 100, 80, 80]
1        [90, 90, 100, 80, 80]
2      [90, 100, 100, 100, 80]
3         [70, 70, 90, 70, 70]
4        [90, 90, 100, 90, 90]
                ...           
169       [80, 80, 80, 80, 70]
170       [80, 90, 80, 80, 80]
171       [80, 90, 80, 80, 80]
172       [70, 80, 70, 70, 70]
173       [70, 80, 70, 70, 70]
Name: label, Length: 174, dtype: object

如何将其转换为 Int dtype?

【问题讨论】:

  • 该列包含作为对象的列表。您正在尝试将列表转换为 int,这将引发错误
  • 不,你没有。您不能将包含列表的列转换为整数数据类型。整个设置也出现了设计问题。为什么列表中的项目没有单独的列?
  • 整列都是列表,但我需要它们是与 tensorflow 兼容的列表的 ind,是整数列表而不是字符串
  • 是整数列表;否则会有引号

标签: python pandas dataframe tensorflow keras


【解决方案1】:

不能在 pandas 中有一个数组 dtype。

但是,有一些替代方案,如果您的最终目标是将数据框提供给 keras 模型,您可以使用以下内容:

import pandas as pd
import numpy as np

s = pd.Series([[1,2,3]] * 5)
df = pd.DataFrame(s.to_list(), dtype='int64')

它快速且易于理解。

那么你可以使用

df.to_numpy()

为您的模型创建一个格式良好的输入数组。如果你使用的是 tensorflow,你也可以使用tf.data 模块来实现同样的效果。

还有其他问题可以问我。
干杯!

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 2013-08-31
    • 2023-01-28
    • 2021-03-04
    • 1970-01-01
    • 2023-01-08
    • 2018-10-01
    • 2011-04-11
    • 2021-11-02
    相关资源
    最近更新 更多