python - 出现错误:“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) )
但是,编译器返回差异租金错误
例外:数据必须是一维的
我可以知道如何解决这个问题吗?
解决方案
你所有的sub_iti, tw, col_iti
都是 2D 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
推荐阅读
- python - 如何使用 cssSelector :nth-child(n) 在 Python Selenium 中定位元素
- php - 使用命令“composer install --no-dev --optimize-autoloader”下载翼龙时出错
- cakephp - 如何修复 Cakephp 4 Composer 安装错误
- model-view-controller - 使用令牌 WebAPI 对 MVC 应用程序进行身份验证
- android - 点击事件上的片段重叠?- 安卓
- javascript - 在 react-native 中从客户端 TCP IP 读取消息
- python-3.x - 如何使用可用于 aws lambda 函数的 goofy 将 s3 存储桶上的文件安装到 aws ec2 实例?
- c++ - 重载减量运算符时使用的额外参数是什么?
- iis - 来自另一台机器的 http 错误 500 内部服务器错误
- java - 如何创建一个通用的 FlatFileItemReader 来读取具有不同标题的 CSV 文件?