簡體   English   中英

如何將 pandas dataframe 轉換為具有列名的 numpy 數組?

[英]How to convert pandas dataframe into the numpy array with column names?

如何將 pandas DataFrame轉換為以下具有列名的 Numpy 數組?

array([('Heidi Mitchell', 'uboyd@hotmail.com', 74, 52, 'female', '1121', 'cancer', '03/06/2018'),
       ('Kimberly Kent', 'wilsoncarla@mitchell-gree', 63, 51, 'male', '2003', 'cancer', '16/06/2017')],
      dtype=[('name', '<U16'), ('email', '<U25'), ('age', '<i4'), ('weight', '<i4'), ('gender', '<U10'), ('zipcode', '<U6'), ('diagnosis', '<U6'), ('dob', '<U16')])

這是我的 pandas DataFrame df

col1  col2
3     5
3     1
4     5    
1     5
2     2

我嘗試將其轉換如下:

import numpy as np

dt = np.dtype([('col1', np.int32), ('col2', np.int32)])
arr = np.array(df.values, dtype=dt)

但它給了我 output 如下:

array([[(3, 5), (3, 1)],
      ...
      dtype=[('col1', '<i4'), ('col2', '<i4')])

由於某種原因,數據行被分組為[(3, 5), (3, 1)]而不是[(3, 5), (3, 1), (4, 5), (1, 5), (1, 2)]

使用 pandas function to_records() ,它將 dataframe 轉換為 Z2EA14541 數組。 鏈接如下: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_records.html

網站中給出的一些示例如下:

>>> df = pd.DataFrame({'A': [1, 2], 'B': [0.5, 0.75]},
                       index=['a', 'b'])
>>> df
   A     B
a  1  0.50
b  2  0.75
>>> df.to_records()
rec.array([('a', 1, 0.5 ), ('b', 2, 0.75)],
          dtype=[('index', 'O'), ('A', '<i8'), ('B', '<f8')])

索引可以從記錄數組中排除:

>>> df.to_records(index=False)
rec.array([(1, 0.5 ), (2, 0.75)],
          dtype=[('A', '<i8'), ('B', '<f8')])

您可以使用df.to_records(index=False)將 dataframe 轉換為結構化數組:

import pandas as pd
data = [ { "col1": 3, "col2": 5 }, { "col1": 3, "col2": 1 }, { "col1": 4, "col2": 5 }, { "col1": 1, "col2": 5 }, { "col1": 2, "col2": 2 } ]
df = pd.DataFrame(data)
df.to_records(index=False)

Output:

rec.array([(3, 5), (3, 1), (4, 5), (1, 5), (2, 2)],
          dtype=[('col1', '<i8'), ('col2', '<i8')])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM