使用python将列表转换为CSV文件

时间:2020-04-27 12:39:19

标签: python python-3.x pandas

我正在尝试使用熊猫将API返回的列表转换为具有行和列的已定义表。
但由于某种原因,它一直返回错误。下面也是我的代码和错误。

import requests
import pprint
import json
import pandas as pd


url = "https://yahoo-finance15.p.rapidapi.com/api/yahoo/ga/topgainers"

querystring = {"start":"0"}

headers = {
    'x-rapidapi-host': "yahoo-finance15.p.rapidapi.com",
    'x-rapidapi-key': "9efd0f3e52mshd859f5daf34a429p11cb2ajsn2b0e421d681e"
    }

response = requests.request("GET", url, headers=headers, params=querystring)
data = response.json()

#print(response.text)


def new_stock(data):
    new_market = []

    for item in data ['quotes']:
        new_name = item.get ('longName')
        new_price = item.get ('regularMarketPrice')
        res_price = (f'{new_price} Dollars')
        cap =item.get('marketCap')
        new_market.append((new_name, res_price, cap))

    return new_market

value = new_stock(data)



def new_list(share_value):
    new = []

    for items in share_value:
        JSONContent = value
        if 'error' not in JSONContent:
            new.append([JSONContent['longName'], JSONContent['regularMarketPrice'], JSONContent['marketCap']])

    return new

dataset = pd.read_csv(new_stock(value))
df = dataset.DataFrame
base = dataset.sample(3)

我不断得到这个错误:

   for item in data ['quotes']:
TypeError: list indices must be integers or slices, not str

2 个答案:

答案 0 :(得分:0)

问题出在dataset = pd.read_csv(new_stock(value))。 此时,value是一个元组列表,而不是您期望的字典。

我认为您错误地尝试使用new_stock函数再次处理它,而不是以某种方式使用您定义的并且未在代码中使用的其他函数(new_list)。

答案 1 :(得分:0)

您为什么不改用json_normalize

response = requests.request("GET", url, headers=headers, params=querystring)
data = response.json()

df = pd.json_normalize(data, ['quotes'])
print(df.head())

  language region quoteType  triggerable currency  ...  earningsTimestamp  earningsTimestampStart  earningsTimestampEnd  epsForward  forwardPE
0       US   ENUS    EQUITY        False      USD  ...                NaN                     NaN                   NaN         NaN        NaN
1       US   ENUS    EQUITY        False      USD  ...       1.584031e+09            1.584031e+09          1.584031e+09       -0.80 -18.237500
2       US   ENUS    EQUITY        False      USD  ...       1.588696e+09            1.588696e+09          1.588696e+09       -7.07 -17.314003
3       US   ENUS    EQUITY        False      USD  ...       1.587672e+09            1.595635e+09          1.596067e+09        0.95  52.452633
4       US   ENUS    EQUITY        False      USD  ...       1.587673e+09            1.595522e+09          1.595867e+09        1.72  26.040697

[5 rows x 71 columns]

您还可以将其保存到csv:

df.to_csv('yahoo.csv')