从两个数组到一个数据框 python

hel*_*isA 1 python arrays numpy dataframe pandas

我试图将我的值放入两个数组中,然后将它们设为数据框。我正在使用 python、numpy 和 pandas 来这样做。

我的数组是:

k = [7.0, 8.0, 6.55, 7.0000001, 10.12]
p = [6.94, 9.0, 4.44444, 13.0, 9.0876]
Run Code Online (Sandbox Code Playgroud)

我想将它们放入熊猫数据框中。当我打印我的数据框时,我想看到这个:

    a     b    c     d     e
k  7.0   8.0  6.6   7.0  10.1
p  6.9   9.0  4.4  13.0   9.1
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

我阅读了一些相关的问题,但我无法正确回答。错误之一是索引不能是元组,但是,如您所见,我没有元组

dat*_*phl 8

您始终pd.DataFrame可以将列表作为输入,这将生成您想要的输出:

k = [7.0, 8.0, 6.55, 7.0000001, 10.12]
p = [6.94, 9.0, 4.44444, 13.0, 9.0876]

pd.DataFrame([k,p],columns=['a','b','c','d','f'],index=['k','p'])

    a   b   c   d   e
k   7.00    8.0 6.55000 7.0 10.1200
p   6.94    9.0 4.44444 13.0    9.0876
Run Code Online (Sandbox Code Playgroud)

如果你想四舍五入:

pd.DataFrame([k,p],columns=['a','b','c','d','f'],index=['k','p']).round()

    a   b   c   d   e
k   7.0 8.0 7.0 7.0 10.0
p   7.0 9.0 4.0 13.0    9.0
Run Code Online (Sandbox Code Playgroud)

对于动态列:

from string import ascii_lowercase
pd.DataFrame([k,p],columns=list(ascii_lowercase[:len(k)]),index=['k','p']).round()
Run Code Online (Sandbox Code Playgroud)

  • 您可以从“string”模块导入“ascii_lowercase”以使列命名动态 (2认同)