【发布时间】:2021-07-21 15:16:58
【问题描述】:
基本上我有一个完整的数字标识符列表——我使用这些数字标识符作为过滤数据帧的条件,然后一旦过滤掉 df,我就会尝试将过滤后的数据帧的长度存储为值在一个新的、单独的数据框中。
我使用我的数字标识符列表中的最后一个值(例如list[-1])作为我循环的停止点——我这样做是为了让循环通过所有标识符运行并在它通过最后一个——我认为这可能是问题所在。
我的代码在遍历列表中的所有唯一数字标识符时吐出所有正确的长度 - 但是,它仍然给我一个索引超出范围错误(如下所示)。
def get_frames(U_id):
k = sorted(df.trackId.unique())
#k is the sorted list of unique numerical identifiers
i = 0
maximum = k[-1] #am using the final value in the list as the stopping point for the loop
while i <= maximum:
condition = df.trackId == k[i]
df2 = df[condition]
values = print(len(df2))
df2 = pd.DataFrame({U_id:values}, index = [i])
i+=1
return df2
get_frames('1CCM0701')
36
18
37
4
33
25
27
49
46
12
45
24
4
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-120-3252dfb603ae> in <module>
13 return df2
14
---> 15 get_frames('1CCM0701')
<ipython-input-120-3252dfb603ae> in get_frames(U_id)
6 maximum = k[-1]
7 while i <= maximum:
----> 8 condition = df.trackId == k[i]
9 df2 = df[condition]
10 values = print(len(df2))
IndexError: list index out of range
【问题讨论】:
标签: python dataframe loops indexing while-loop