gpt4 book ai didi

python - 值的长度与索引的长度不匹配

转载 作者:行者123 更新时间:2023-12-04 01:55:32 26 4
gpt4 key购买 nike

向 Stackoverflow 社区问好,

我正在尝试读取一个包含 1370 行和两列的 .csv 文件:TimeSpeed

Time   Speed

0 1

1 4

2 7

3 8

我想找出两个时间步长之间Speed 的差异(例如Time 21,对于数据的整个长度,它是 3)。我想添加一个新列 dS,其中包含之前计算的差值。数据现在看起来像:

Time   Speed  dS

0 1 NaN

1 4 3

2 7 3

3 8 1

我使用的代码如下:

import pandas as pd
from pandas import read_csv

df2 = pd.read_csv ('speed.csv')

dVV = []


for i, row in df2.iterrows():
dVV.append(df2.iloc[i+1,1] - df2.iloc[i,1])
break

df2['dVV']=dVV

我得到的错误是:

ValueError                                Traceback (most recent call last)
<ipython-input-29-4ed9fde37ff9> in <module>()
14 break
15
---> 16 df2['dVV']=dVV
17
18 #df2.to_csv('udds_test.csv', index=False, header=True)

~\Anaconda3\lib\site-packages\pandas\core\frame.py in __setitem__(self, key,
value)
2517 else:
2518 # set column
-> 2519 self._set_item(key, value)
2520
2521 def _setitem_slice(self, key, value):

~\Anaconda3\lib\site-packages\pandas\core\frame.py in _set_item(self, key,
value)
2583
2584 self._ensure_valid_index(value)
-> 2585 value = self._sanitize_column(key, value)
2586 NDFrame._set_item(self, key, value)
2587

~\Anaconda3\lib\site-packages\pandas\core\frame.py in _sanitize_column(self, key, value, broadcast)
2758
2759 # turn me into an ndarray
-> 2760 value = _sanitize_index(value, self.index, copy=False)
2761 if not isinstance(value, (np.ndarray, Index)):
2762 if isinstance(value, list) and len(value) > 0:

~\Anaconda3\lib\site-packages\pandas\core\series.py in _sanitize_index(data,
index, copy)
3119
3120 if len(data) != len(index):
-> 3121 raise ValueError('Length of values does not match length of '
'index')
3122
3123 if isinstance(data, PeriodIndex):

ValueError: Length of values does not match length of index

我猜测代码在最后 1370 行之后被破坏了。我该如何解决这个问题?

最佳答案

你可以只使用pd.Series.diff :

df['ds'] = df['Speed'].diff()

print(df)

Time Speed ds
0 0 1 NaN
1 1 4 3.0
2 2 7 3.0
3 3 8 1.0

pd.Series.diff 等矢量化解决方案可用时,不推荐您尝试的循环方法。

关于python - 值的长度与索引的长度不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50913172/

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