【问题标题】:Creation of DataFrame from some numpy arrays从一些 numpy 数组创建 DataFrame
【发布时间】:2018-06-13 13:59:42
【问题描述】:

我是使用 Python 的新手,我在从 numpy 数组创建 pandas DataFrame 时遇到了一些问题。

我有 3 个数组:

import numpy as np

a = np.array([3, 6, 9, 12, 15, 18, 21, 24, 27, 30])
b = np.array([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
x = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1])

我需要构建一个数据框,其中 x 应该是列的名称,它将有 5 行命名为 (x1, x2, x3, x4, x5)。并且 DataFrame 应该用数组的值来实现。

x | 0.1|0.2|0.3|....


x1 | 2 | 4 | 6 ....


x2 | 2 | 4 | 6 ....


x3 | 3 | 6 | 9 ....


x4 | 3 | 6 | 9 ....


x5 | 2 | 4 | 6 ....

感谢您的帮助

【问题讨论】:

    标签: python pandas numpy dataframe


    【解决方案1】:

    你可以使用

    import pandas as pd
    
    pd.DataFrame([b, b, a, a, b], columns=x, index=['x{}'.format(i+1) for i in range(5)])
    

    这给出了:

        0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9  1.0
    x1    2    4    6    8   10   12   14   16   18   20
    x2    2    4    6    8   10   12   14   16   18   20
    x3    3    6    9   12   15   18   21   24   27   30
    x4    3    6    9   12   15   18   21   24   27   30
    x5    2    4    6    8   10   12   14   16   18   20
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-08
      • 2016-07-14
      • 1970-01-01
      • 2017-12-30
      • 1970-01-01
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多