【问题标题】:Converting Numpy Structured Array to Pandas Dataframes将 Numpy 结构化数组转换为 Pandas 数据帧
【发布时间】:2018-12-31 07:23:03
【问题描述】:

我从以下代码中获得了一个结构化的 numpy 数组:

data = np.genfromtxt(fname, dtype = None, comments = '#', skip_header=1, usecols=(ucols))

其中第一列是以乱序排列的其余数据集的索引(我希望保留)。 我想将结构化数组转换为 Pandas 数据帧,并将加扰索引作为数据帧的可调用索引。

编辑:

import numpy as np

test = np.array([(45,1,'mars',1,1),(67,1,'pluto',1,1),(12,1,'saturn',1,1)],dtype='i,f,U10,i,f')

创建一个 numpy 结构化数组,调用第一个条目给出:

In [5]: test[0]
Out[5]: (45, 1., 'mars', 1, 1.)

调用整个数组:

In [6]: test
Out[6]: 
array([(45, 1., 'mars', 1, 1.), (67, 1., 'pluto', 1, 1.),
       (12, 1., 'saturn', 1, 1.)],
      dtype=[('f0', '<i4'), ('f1', '<f4'), ('f2', '<U10'), ('f3', '<i4'), ('f4', '<f4')])

我想把这个结构化数组变成一个 pandas 数据框,然后在这个例子中让 45,67,12 成为访问数组“行”中数据的可调用索引。

【问题讨论】:

标签: python python-3.x pandas numpy


【解决方案1】:

假设你已经完成了import pandas as pd

df = pd.DataFrame(test) # converts your array to a DataFrame.
df = df.set_index('f0') # changes the index to be the first column.

【讨论】:

  • 我发布的代码创建了一个 numpy 结构化数组,我想将此结构化数组转换为 pandas 数据帧,第一列作为数据帧的可调用索引
【解决方案2】:

对于给定的例子,你可以让

df = pd.DataFrame(test).set_index('f0')

这样,您可以访问索引为 45 到 df.loc[45] 的行。

【讨论】:

    猜你喜欢
    • 2020-06-25
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 2021-04-04
    相关资源
    最近更新 更多