【发布时间】:2020-08-14 07:03:48
【问题描述】:
我正在尝试使用 pandas 将字典项转换为表格,但问题是我没有得到想要的结果。 下面是我的代码
value = new_stock(data)
dict_stocks = {i: value[i] for i in range (0, len(value))}
df = pd.DataFrame(list(dict_stocks.items()), columns =['Company Name', 'Price per share', Total valuation])
print(df)
我希望输出像
Company name price per share Total valuation
Norwegian Cruise Line Holdings Ltd.', '16.41 Dollars', '3498661376 billion dollars'
Carnival Corporation & Plc', '15.5 Dollars', '10927298560 billion dollars'
但我的输出是这种格式。
Company Name Price per share
0 0 (Norwegian Cruise Line Holdings Ltd., 16.41 Do...
1 1 (Carnival Corporation & Plc, 15.5 Dollars, 109...
2 2 (Noble Energy, Inc., 10.05 Dollars, 4874652160...
3 3 (Apache Corporation, 13.05 Dollars, 4925304832...
4 4 (Companhia Siderurgica Nacional, 1.66 Dollars,...
5 5 (DCP Midstream, LP, 10.03 Dollars, 2089549824 ...
6 6 (Sabre Corporation, 7.4 Dollars, 2025794432 bi...
7 7 (Sasol Limited, 5.13 Dollars, 3016778496 billi...
8 8 (Continental Resources, Inc., 15.85 Dollars, 5...
9 9 (Marathon Oil Corporation, 5.85 Dollars, 46239...
10 10 (AerCap Holdings N.V., 28.47 Dollars, 37461678...
11 11 (Penn National Gaming, Inc., 18.61 Dollars, 21...
12 12 (Royal Caribbean Cruises Ltd., 48.06 Dollars, ...
13 13 (Canadian Natural Resources Limited, 17.38 Dol...
14 14 (WPX Energy, Inc., 6.08 Dollars, 3400939008 bi...
15 15 (Ryman Hospitality Properties, Inc., 37.78 Dol...
16 16 (TechnipFMC plc, 9.27 Dollars, 4124464384 bill...
17 17 (Diamondback Energy, Inc., 44.19 Dollars, 6973...
18 18 (Santander Consumer USA Holdings Inc., 17.05 D...
19 19 (Marathon Petroleum Corporation, 33.04 Dollars...
20 20 (Air Lease Corporation, 26.72 Dollars, 3036327...
21 21 (Carnival Corporation & Plc, 16.69 Dollars, 13...
22 22 (Howmet Aerospace Inc., 13.89 Dollars, 6054915...
23 23 (Aaron's, Inc., 32.33 Dollars, 2184589824 bill...
24 24 (Tata Motors Limited, 5.88 Dollars, 3851547136...
如果提供任何帮助,我将不胜感激
******附加**** 这是剩下的部分代码
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')
if cap >= 1000000000:
cap = f'{cap} billion dollars'
else:
cap = f'{cap} million dollars'
new_market.append((new_name, res_price, cap))
return new_market
value = new_stock(data)
【问题讨论】:
-
你能分享变量值的一个子集吗?
-
请分享您的
dictionary。 -
@MayankPorwal 更新
-
@datanovice 更新
标签: python pandas dictionary tuples