gpt4 book ai didi

python - 错误 : list indices must be integers, 不是系列

转载 作者:太空宇宙 更新时间:2023-11-03 17:45:51 27 4
gpt4 key购买 nike

我从 pandas 数据框中抓取了一列,并从行中创建了一个列表。如果我打印列表的前两个值,我会得到以下输出:

print dfList[0]
print dfList[1]

0 0.00
1 0.00
2 0.00
3 0.00
4 0.00
5 0.11
6 0.84
7 1.00
8 0.27
9 0.00
10 0.52
11 0.55
12 0.92
13 0.00
14 0.00
...
50 0.42
51 0.00
52 0.00
53 0.00
54 0.40
55 0.65
56 0.81
57 1.00
58 0.54
59 0.21
60 0.00
61 0.33
62 1.00
63 0.75
64 1.00
Name: 9, Length: 65, dtype: float64
65 1.00
66 1.00
67 1.00
68 1.00
69 1.00
70 1.00
71 0.55
72 0.00
73 0.39
74 0.51
75 0.70
76 0.83
77 0.87
78 0.85
79 0.53
...
126 0.83
127 0.83
128 0.83
129 0.71
130 0.26
131 0.11
132 0.00
133 0.00
134 0.50
135 1.00
136 1.00
137 0.59
138 0.59
139 0.59
140 1.00
Name: 9, Length: 76, dtype: float64

当我尝试使用 for 循环迭代列表时,收到一条错误消息:

for i in dfList:
print dfList[i]

Traceback (most recent call last):
File "./windows.py", line 84, in <module>
print dfList[i]
TypeError: list indices must be integers, not Series

如果我将代码编写为:

for i in dfList:
print i

我得到了正确的输出:

0     0.00
1 0.00
2 0.00
3 0.00
4 0.00
5 0.11
6 0.84
7 1.00
8 0.27
9 0.00
10 0.52
11 0.55
12 0.92
13 0.00
14 0.00
...
50 0.42
51 0.00
52 0.00
53 0.00
54 0.40
55 0.65
56 0.81
57 1.00
58 0.54
59 0.21
60 0.00
61 0.33
62 1.00
63 0.75
64 1.00
Name: 9, Length: 65, dtype: float64
...
...
Name: 9, Length: 108, dtype: float64
507919 0.00
507920 0.83
507921 1.00
507922 1.00
507923 0.46
507924 0.83
507925 1.00
507926 1.00
507927 1.00
507928 1.00
507929 1.00
507930 1.00
507931 1.00
507932 1.00
507933 1.00
...
508216 1
508217 1
508218 1
508219 1
508220 1
508221 1
508222 1
508223 1
508224 1
508225 1
508226 1
508227 1
508228 1
508229 1
508230 1
Name: 9, Length: 312, dtype: float64

我不知道为什么会发生这种情况。

我最终想要迭代 5 个连续“窗口”的列表并计算它们的平均值并将这些平均值放入列表中。

最佳答案

在Python中,当您编写for i in时,i是元素,而不是您需要的索引,然后打印i而不是打印 dfList[i].

以下两个选项都可以:

for i in dfList[i]:
print i

for i in range(len(dfList)):
print dfList[i]

第一个更加Pythonic和优雅,除非你需要索引。

编辑

正如 jwilner 建议的那样,您也可以这样做:

for i, element in enumerate(dfList):
print i, element

这里i是索引,elementdfList[i]

关于python - 错误 : list indices must be integers, 不是系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29810920/

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