【问题标题】:Getting Error: "ValueError: If using all scalar values, you must pass an index" when converting ndarray to pandas Dataframe出现错误:“ValueError:如果使用所有标量值,则必须传递索引”将 ndarray 转换为 pandas Dataframe
【发布时间】:2021-06-01 03:27:52
【问题描述】:

根据以下代码将多个ndarray 转换为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) )

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

例外:数据必须是一维的

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

【问题讨论】:

标签: python pandas numpy


【解决方案1】:

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

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

Pandas 期望它们是 1D numpy 数组或列表,因为 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

【讨论】:

  • 在拉威尔上加一个
猜你喜欢
  • 2017-02-19
  • 2013-07-24
  • 2021-07-14
  • 2016-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多