将pandas数据框转换为结构化数组。

4

我有以下的pandas数据框:

import pandas as pd
a = [2.5,3.3]
b = [3.6,3.9]
D = {'A': a, 'B': b}

这让我得到了类似于以下内容:

+---+-----+-----+
|   |  A  |  B  |
+---+-----+-----+
| 0 | 2.5 | 3.3 |
| 1 | 3.6 | 3.9 |
+---+-----+-----+ 

我想将这个数据框转换为一个结构化数组,如下所示:
data = np.rec.array([
('A', 2.5),
('A', 3.6),
('B', 3.3),
('B', 3.9),
], dtype = [('Type','|U5'),('Value', '<i8')])

由于我对pandas不熟悉,我找不到实现这一点的方法。我尝试使用pd.to_records,但是索引成为了问题,我无法解决。

非常感谢您的帮助。

4个回答

9

融合DataFrame,将AB(列索引)转换为一列。为了去除数字索引,将这个新列作为索引。然后调用to_records()

import pandas as pd
a = [2.5,3.3]
b = [3.6,3.9]
D = {'A': a, 'B': b}
df = pd.DataFrame(D)
result = (pd.melt(df, var_name='Type', value_name='Value')
          .set_index('Type').to_records())
print(repr(result))

产量
rec.array([('A',  2.5), ('A',  3.3), ('B',  3.6), ('B',  3.9)], 
          dtype=[('Type', 'O'), ('Value', '<f8')])

这是关键步骤:
In [167]: df
Out[167]: 
     A    B
0  2.5  3.6
1  3.3  3.9

In [168]: pd.melt(df)
Out[168]: 
  variable  value
0        A    2.5
1        A    3.3
2        B    3.6
3        B    3.9

一旦您将DataFrame转换为数组,to_records(基本上)返回所需的结果:

In [169]: pd.melt(df).to_records()
Out[169]: 
rec.array([(0, 'A',  2.5), (1, 'A',  3.3), (2, 'B',  3.6), (3, 'B',  3.9)], 
          dtype=[('index', '<i8'), ('variable', 'O'), ('value', '<f8')])

1
运行得非常好。非常感谢@unutbu! - Xiaoyu Lu

3

这对我来说没有融化的问题。

pandas版本:1.5.2,numpy版本:1.23.5,Python 3.10.4

records = df.to_records(index=False)
data = np.array(records, dtype = records.dtype.descr)

2
np.rec.fromrecords(list(zip(df.melt().variable,df.melt().value)))
Out[531]: 
rec.array([('A',  2.5), ('A',  3.3), ('B',  3.6), ('B',  3.9)], 
          dtype=[('f0', '<U1'), ('f1', '<f8')])

0

你可以使用 melt 和 call to_records:

pd.melt(df).to_records(index=False)

这将返回np.recarray,而不是结构化的np.ndarray;我已经测试过了,并在事后转换为np.ndarray;使用pd.melt(df).to_records(index=False).view(np.ndarray)似乎不能得到期望的结果。df.to_records(index=False).view(np.ndarray)似乎可以工作,但似乎会产生与其他答案略有不同的类型。 - MRule

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接