【问题标题】:Pandas dataframe.to_numpy() with specific dtypes具有特定 dtypes 的 Pandas dataframe.to_numpy()
【发布时间】:2020-10-28 17:25:57
【问题描述】:

我有一个包含两列的数据框:

  In[] df.head()

  Out[]      specific_death   months_survival
       0         False            179
       1         False            127
       2         False            67
       3         True             111
       4         False            118

第一列是布尔值,第二列是整数。如果我将数据框转换为 numpy ndarray :

array_from_df = df.to_numpy()

我得到一个非结构化的 numpy.ndarray。因此,如果我写:

array_from_df.dtype.fields 

结果是 NoneType。为了使我的程序正常工作,我需要一个结构化数组,其中第一个字段是 np.bool 类,第二个字段是 np.int。我看到它的方式有两种选择,但我找不到任何一种方法:

选项一

直接从 Pandas.DataFrame 转换为具有正确 dtypes 的结构化 numpy.ndarray。

选项二

从 Pandas.DataFrame 转换为非结构化的 numpy.ndarray,然后将其转换为结构化的 numpy.ndarray。 I found another SO question 关于这个问题,但我无法在我的代码上复制答案。

【问题讨论】:

  • 也许this method 应该做你想做的事
  • df.to_records(index=False) 应该完成这项工作,不是吗?有关更多选项,请参阅 this answer 例如。
  • 感谢两位的快速回答,我觉得 Pandas 还没有实现单线来完成这个技巧让我觉得很奇怪。

标签: python pandas numpy dataframe structured-array


【解决方案1】:

正如两位 cmets 所建议的那样:

array_from_df = df.to_records() # index=False to not include an index column

输出具有正确数据类型的 numpy.recarray:

array_from_df.dtype.fields 

【讨论】:

    猜你喜欢
    • 2020-08-06
    • 2016-12-24
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2019-04-18
    • 2017-01-10
    相关资源
    最近更新 更多