gpt4 book ai didi

python-3.x - 值错误 : arrays must all be same length in python using pandas DataFrame

转载 作者:行者123 更新时间:2023-12-03 23:43:34 29 4
gpt4 key购买 nike

我是 python 的新手,使用 Pandas 包 (python3.6) 中的 Dataframe。

我像下面的代码一样设置它,

df = DataFrame({'list1': list1, 'list2': list2, 'list3': list3, 'list4': list4, 'list5': list5, 'list6': list6})

它给出了类似 ValueError: arrays must all be same length 的错误

所以我检查了所有数组的长度,和 list1 & list2比其他列表多 1 个数据。如果我想使用 list3 将 1 个数据添加到其他 4 个列表( list4list5list6pd.resample )中,那我应该怎么写代码...?

此外,这些列表是 1 分钟的时间序列列表。

有人有想法或帮助我吗?

提前致谢。

编辑
所以我改变了 EdChum 所说的。
并在前面添加了时间表。就像下面一样。
2017-04-01 0:00 895.87  730 12.8    4   19.1    380
2017-04-01 0:01 894.4 730 12.8 4 19.1 380
2017-04-01 0:02 893.08 730 12.8 4 19.3 380
2017-04-01 0:03 890.41 730 12.8 4 19.7 380
2017-04-01 0:04 889.28 730 12.8 4 19.93 380

我输入了类似的代码
df.resample('1min', how='mean', fill_method='pad')

它给了我这个错误: TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'

最佳答案

我只是构建一个 Series对于每个列表,然后 concat 商场:

In [38]:
l1 = list('abc')
l2 = [1,2,3,4]
s1 = pd.Series(l1, name='list1')
s2 = pd.Series(l2, name='list2')
df = pd.concat([s1,s2], axis=1)
df

Out[38]:
list1 list2
0 a 1
1 b 2
2 c 3
3 NaN 4

因为你可以通过 name arg 为 Series ctor 它将命名 df 中的每一列,加上它会放置 NaN列长度​​不匹配的地方
resample指的是当您有 DatetimeIndex您想根据某个时间段重新调整或调整长度,这不是您在这里想要的。您要 reindex我认为这是不必要的和凌乱的:
In [40]:
l1 = list('abc')
l2 = [1,2,3,4]
s1 = pd.Series(l1)
s2 = pd.Series(l2)
df = pd.DataFrame({'list1':s1.reindex(s2.index), 'list2':s2})
df

Out[40]:
list1 list2
0 a 1
1 b 2
2 c 3
3 NaN 4

在这里你需要知道最长的长度,然后 reindex使用该索引的所有系列,如果您只是 concat它会自动调整长度并用 NaN 填充缺失的元素

关于python-3.x - 值错误 : arrays must all be same length in python using pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45051882/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com