简体   繁体   English

如何将 200 列 numpy 数组转换为 dataframe?

[英]How to convert 200 column numpy array to dataframe?

I have a numpy with 200 columns.我有一个 numpy 有 200 列。 Now, I want to store this with the column names in a datagram.现在,我想将其与列名一起存储在数据报中。 How do I do this?我该怎么做呢?

array([[0.47692407, 0.29395011, 0.54361545, ..., 0.        , 0.69314718,
        0.        ],
       [0.        , 0.41974993, 0.40546511, ..., 0.        , 0.69314718,
        0.        ],
       [0.47692407, 0.53776803, 0.54361545, ..., 0.        , 0.69314718,...]

#column names
df.columns=['a','b',.......'200th column name']

I have something like: 
pd.DataFrame(arr, columns=df.columns) but i get an error: "AttributeError: 'numpy.ndarray' object has no attribute 'columns'"

When I searched, I mostly find examples with are concerned with a few column names which makes it easier if manually coded.当我搜索时,我发现大多数示例都与一些列名称有关,如果手动编码,这些名称会更容易。 In my situation, it needs to be more programmatic due to the high number of columns.在我的情况下,由于列数较多,它需要更具编程性。 Please advise.请指教。

You can generate dynamically columns with a list comprehension iterating on the number of columns.您可以使用对列数进行迭代的列表理解来动态生成列。

import numpy as np
import pandas as pd
dd = np.reshape(np.arange(20), (5,4))
pd.DataFrame(dd, columns=['col{0:03d}'.format(k) for k in range(dd.shape[1])])

That gives:这给出了:

   col000  col001  col002  col003
0       0       1       2       3
1       4       5       6       7
2       8       9      10      11
3      12      13      14      15
4      16      17      18      19

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM