首页 > 解决方案 > 出现错误:“ValueError:如果使用所有标量值,则必须传递索引”将 ndarray 转换为 pandas Dataframe

问题描述

根据以下代码将多个转换ndarray为 a时df

import  numpy as np
import pandas as pd

ls_a = ['TA', 'BAT', 'T']
xxx = ['xx', 'cc']

feature_no = len(ls_a)
windows_no = len(xxx)


sub_iti = np.repeat([['s1']], (feature_no * windows_no), axis=0).reshape(-1, 1)
tw = np.repeat([xxx], feature_no, axis=1).reshape(-1, 1)
col_iti = np.repeat([ls_a], windows_no, axis=0).reshape(-1, 1)

df=pd.DataFrame ({'sub_iti': sub_iti,'tw': tw,'col_iti': col_iti})

, 编译器返回错误

ValueError:如果使用所有标量值,则必须传递索引

基于OP,参数index输入如下

 df=pd.DataFrame (
             {'sub_iti': sub_iti,
              'tw': tw,
              'col_iti': col_iti},index=range(0,3*2) )

但是,编译器返回差异租金错误

例外:数据必须是一维的

我可以知道如何解决这个问题吗?

标签: pythonpandasnumpy

解决方案


你所有的sub_iti, tw, col_iti都是 2D numpy 数组。但是,当您这样做时:

df=pd.DataFrame ({'sub_iti': sub_iti,
                   'tw': tw,
                   'col_iti': col_iti} )

Pandas 期望它们是1Dnumpy 数组或列表,因为 DataFrame 的列应该是这样的。你可以试试:

df=pd.DataFrame ({'sub_iti': sub_iti.tolist(),
                 'tw': tw.tolist(),'col_iti': col_iti.tolist()})

输出:

  sub_iti    tw col_iti
0    [s1]  [xx]    [TA]
1    [s1]  [xx]   [BAT]
2    [s1]  [xx]     [T]
3    [s1]  [cc]    [TA]
4    [s1]  [cc]   [BAT]
5    [s1]  [cc]     [T]

但我确实认为你应该删除每个单元格内的列表,并使用ravel()而不是tolist()

df=pd.DataFrame ({'sub_iti': sub_iti.ravel(),
                 'tw': tw.ravel(),'col_iti': col_iti.ravel()})

输出:

  sub_iti  tw col_iti
0      s1  xx      TA
1      s1  xx     BAT
2      s1  xx       T
3      s1  cc      TA
4      s1  cc     BAT
5      s1  cc       T

推荐阅读