简体   繁体   English

从 numpy 艾莉亚创建 pandas df

[英]create pandas df from numpy arrya

I have a numpy array that has values for each column in each subarray [[column one info], [column2 info], [column3 info]]我有一个 numpy 数组,每个子数组中的每一列都有值[[column one info], [column2 info], [column3 info]]

I have tried this:我试过这个:

df = pd.DataFrame(data = tarray, index=tindex, columns=column_values)

I have also tried this我也试过这个

df = pd.DataFrame(tarray, tindex, column_values)

this is the entire code block这是整个代码块

import numpy as np
import pandas as pd
tzip = 76000
tname = ['rest1', 'rest2', 'rest3', 'rest4']
taddy = ['1234 main', '1235 main', '1236 main', '1237 main']
column_values = ['zipcode', 'restaurant_name', 'address']
tzip_arr = []
tindex = []
for x in range(len(tname)):
    tindex.append(x)
    tzip_arr.append(tzip)
tarray = np.array([tzip_arr,tname,taddy])
df = pd.DataFrame(tarray, tindex, column_values)
print(df)

now finally the error I'm getting is ValueError: Shape of passed values is (3, 4), indices imply (4, 3)现在终于我得到的错误是ValueError: Shape of passed values is (3, 4), indices imply (4, 3)

Possible solution is the following:可能的解决方案如下:

import numpy as np
import pandas as pd

tzip = 76000
tname = ['rest1', 'rest2', 'rest3', 'rest4']
taddy = ['1234 main', '1235 main', '1236 main', '1237 main']
column_values = ['zipcode', 'restaurant_name', 'address']

tzip_arr = []

for x in range(len(tname)):
    tzip_arr.append(tzip)

tarray = np.array([tzip_arr,tname,taddy])
df = pd.DataFrame(data=tarray.T, columns=column_values)

df

Returns退货

在此处输入图像描述

The problem was that you didnt have the np array in the right shape, therefore you need to reshape it like that问题是你没有正确形状的 np 数组,因此你需要像那样重塑它

df = pd.DataFrame(tarray.reshape(3,4).transpose(), tindex, column_values)

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

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