如何解决TypeError:列表索引必须是整数,而不是列表? [英] How to solve TypeError: list indices must be integers, not list?

查看:211
本文介绍了如何解决TypeError:列表索引必须是整数,而不是列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以json格式下载数据并将其保存到数据框中.

I am downloading data in json format and saving it into a data frame.

data = []
for day in range(9,10):
       request=Request('https://api..../10/'+str(day)+'/'+appId='+appID+')
       response = urlopen(request)
       arrivals = response.read()
       d = json.loads(arrivals)
       data.append(json_normalize(d['Statuses']))

data[column_names].to_csv("data.csv")

但是此代码的最后一行提供了一个错误:

However the last line of this code provides an error:

TypeError: list indices must be integers, not list

看起来data是一个列表.我尝试如下创建data:data = pandas.DataFrame(),但是也出现错误. 如何解决这个问题?

It looks like data is a list. I tried create data as follows: data = pandas.DataFrame(), but there was also an error. How to solve this issue?

推荐答案

您的data是一个列表,正如您在开始时定义的那样-data = []-因此,当您尝试使用另一个列表访问它们时column_names ,您会得到错误.

Your data is a list, as you define it at the start - data = [] - Hence when you trying to access them using another list column_names , you get the error you are getting.

如果您尝试连接从不同请求获得的不同数据帧,则应使用data上使用rel ="nofollow"> pandas.concat 将列表中的所有数据框连接到一个数据框中. org/pandas-docs/stable/generation/pandas.DataFrame.to_csv.html"rel =" nofollow> to_csv 放在上面.示例-

If you are trying to concatenate the different dataframes you get from the different requests, you should use pandas.concat on data to concatenate all the dataframes from the list into a single dataframe, before accessing its columns and using to_csv on it. Example -

data[column_names].to_csv("data.csv")

应更改为-

pd.concat(data)[column_names].to_csv("data.csv")

这篇关于如何解决TypeError:列表索引必须是整数,而不是列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆