【问题标题】:convert numpy array into dataframe [duplicate]将numpy数组转换为数据框[重复]
【发布时间】:2021-03-26 09:51:43
【问题描述】:

我有一个 numpy 数组,我想将其转换为数据框。

import numpy as np
import pandas as pd    
nparray = np.array([[1,2,3,4,5],[6,7,8,9,10]])

如何将其转换为数据如下所示的数据框:

col1 col2
1      6
2      7
3      8
4      9
5      10

【问题讨论】:

  • 不,我之前检查过那个答案。但我无法理解如何转置数组。我有很多东西要学:)

标签: python pandas dataframe numpy


【解决方案1】:

我最喜欢将 numpy 数组转换为 pandas DataFrames 的方法是传递字典中的列:

df = pd.DataFrame({'col1':nparray[0], 'col2':nparray[1]})

但是,如果你有很多列,你可以试试:

# Create list of column names with the format "colN" (from 1 to N)
col_names = ['col' + str(i) for i in np.arange(nparray.shape[0]) + 1]
# Declare pandas.DataFrame object
df = pd.DataFrame(data=nparray.T, columns=col_names)

在第二种解决方案中,您必须在将数组传递给data = ... 之前对其进行重组。也就是说,您必须重新排列 nparray 以便它具有行和列。 Numpy 有一个方法:你只需将.T 添加到你的数组中:nparray.T

【讨论】:

    【解决方案2】:

    使用以下代码将 numpy 数组转换为 DF。

    df = pd.DataFrame(nparray.T, columns=['col1', 'col2'])
    

    【讨论】:

      【解决方案3】:
      pd.DataFrame(nparray.T, columns=['col1', 'col2'])
      

      就是这样

      【讨论】:

        【解决方案4】:

        你可以转置你的 np 数组

        创建数组

        >>> import numpy as np
        >>> import pandas as pd
        >>> nparray = np.array([[1,2,3,4,5],[6,7,8,9,10]])
        
        >>> nparray
        array([[ 1,  2,  3,  4,  5],
               [ 6,  7,  8,  9, 10]])
        

        创建 pandas DataFrame 并转置

        >>> df = pd.DataFrame(data=nparray, index=["col1", "col2"]).transpose()
        
        >>> df
           col1  col2
        0     1     6
        1     2     7
        2     3     8
        3     4     9
        4     5    10
        

        及时 - 不用转置你会得到:

        >>> df = pd.DataFrame(data=nparray, index=["col1", "col2"])
        
        >>> df
              0  1  2  3   4
        col1  1  2  3  4   5
        col2  6  7  8  9  10
        

        【讨论】:

          猜你喜欢
          • 2019-07-25
          • 2018-05-03
          • 2017-05-09
          • 2021-12-20
          • 2017-11-09
          • 2020-06-20
          • 1970-01-01
          • 2021-11-29
          相关资源
          最近更新 更多