![](/img/trans.png)
[英]How can I transform a list of tuples into a pandas dataframe so that the first value of each tuple represents a column?
[英]How do I join six list of tuples into a pandas dataframe using the first value of each tuple as the key?
我正在测试一个服务,它有一个可以从中提取解析的 10K 公司数据的 api。 对于提取的每个指标(EBIT、现金、总资产等),我将季度日期和指标存储在一个元组中,并将每个元组存储在一个列表中。 结果是 43 - 80 个元组的六个列表。 我想要一个包含公司代码、日期和指标列的数据框。 我如何将我拥有的(元组列表)变成那个?
下面的代码用于提取数据(这是示例,因此不收费):
import numpy as np
import json
import pandas as pd
content = requests.get(r'https://eodhistoricaldata.com/api/fundamentals/AAPL.US?api_token=OeAFFmMliFG5orCUuwAKQ8l4WWFQ67YX')
ebit_list = []
date_list = []
totalassets_list = []
cash_list = []
totalCurrentAssets_list = []
totalCurrentLiabilities_list = []
for i in content.json()['Financials']['Income_Statement']['quarterly']:
try:
ebit_list.append((i, float(content.json()['Financials']['Income_Statement']['quarterly'][i]['ebit'])))
except:
pass
try:
date_list.append(i)
except:
pass
try:
totalassets_list.append((i, float(content.json()['Financials']['Balance_Sheet']['quarterly'][i]['totalAssets'])))
except:
pass
for i in content.json()['Financials']['Balance_Sheet']['quarterly']:
#print(i, float(content.json()['Financials']['Balance_Sheet']['quarterly']['2019-12-28']['totalCurrentLiabilities']))
try:
cash_list.append((i, float(content.json()['Financials']['Balance_Sheet']['quarterly'][i]['cash'])))
except:
pass
try:
totalCurrentAssets_list.append((i, float(content.json()['Financials']['Balance_Sheet']['quarterly'][i]['totalCurrentAssets'])))
except:
pass
try:
totalCurrentLiabilities_list.append((i, float(content.json()['Financials']['Balance_Sheet']['quarterly'][i]['totalCurrentLiabilities'])))
except:
pass
我想要一个包含所有日期的数据框(意味着如果缺少指标,则填充零)和以下列:
date
、 ebit
、 totalassets
、 cash
、 totalCurrentAssets
、 totalCurrentLiabilities
我不确定如何提取每个元组中的元组和值。
您可以使用pandas.Series
中的map
函数将日期与您需要的数据进行匹配。 这将为没有匹配值的单元格插入NaN
,这将使以后更容易处理丢失的数据。 如果你还想填零,你可以使用fillna
# Create a dataframe using date
df = pd.DataFrame({'date': date_list})
# To avoid the code getting messy in the next steps
stuff = {'ebit': ebit_list, 'totalassets': totalassets_list, 'cash': cash_list, 'totalCurrentAssets': totalCurrentAssets_list, 'totalCurrentLiabilities': totalCurrentLiabilities_list}
for name, values in stuff.items():
value_dict = {t[0]: t[1] for t in values} # t is each tuple in the list
df[name] = df['date'].map(value_dict) # map will match the correct date to the value
# assuming you need the dataframe to be sorted by date
df['date'] = pd.to_datetime(df['date']) # we should use actual numbers instead of date string
df.sort_values('date', inplace=True, ignore_index=True)
# if you want to fill 0s to missing values
# df.fillna(0, inplace=True)
sort_values
ignore_index
参数是为了确保排序后索引不会混乱。 如果你的pandas
版本是旧的,可能会给一个TypeError: sort_values() got an unexpected keyword argument 'ignore_index'
排序时。 如果是这样,您应该使用以下内容来重置索引
df.sort_values('date', inplace=True)
df.reset_index(inplace=True)
最后这是 df
date ebit totalassets cash totalCurrentAssets totalCurrentLiabilities
0 2000-03-31 NaN 7.007000e+09 NaN NaN 1.853000e+09
1 2000-06-30 NaN 6.932000e+09 NaN NaN 1.873000e+09
2 2000-09-30 NaN 6.803000e+09 NaN NaN 1.933000e+09
3 2000-12-31 0.000000e+00 5.986000e+09 NaN NaN 1.637000e+09
4 2001-03-31 0.000000e+00 6.130000e+09 NaN NaN 1.795000e+09
.. ... ... ... ... ... ...
75 2018-12-29 2.334600e+10 3.737190e+11 4.477100e+10 1.408280e+11 1.082830e+11
76 2019-03-30 1.341500e+10 3.419980e+11 3.798800e+10 1.233460e+11 9.377200e+10
77 2019-06-29 1.154400e+10 3.222390e+11 5.053000e+10 1.349730e+11 8.970400e+10
78 2019-09-28 1.562500e+10 3.385160e+11 4.884400e+10 1.628190e+11 1.057180e+11
79 2019-12-28 2.556900e+10 3.406180e+11 3.977100e+10 1.632310e+11 1.021610e+11
我无法让您的示例工作,请求未定义。
但这里有一些代码可以做你想要的:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
def create_df(list_of_lists):
pd.DataFrame({x[0]: pd.Series(x[1:]) for x in list of lists})
我们实际上可以大大简化此代码以获得您想要的结果(并使其在将来更容易调整!)
完成的代码在这里,下面有更详细的解释:
import numpy as np
import json
import pandas as pd
import requests
content = requests.get(r'https://eodhistoricaldata.com/api/fundamentals/AAPL.US?api_token=OeAFFmMliFG5orCUuwAKQ8l4WWFQ67YX')
income_data = content.json()['Financials']['Income_Statement']['quarterly']
income = pd.DataFrame.from_dict(income_data).transpose().set_index("date")
income = income[['ebit']]
balance_data = content.json()['Financials']['Balance_Sheet']['quarterly']
balance = pd.DataFrame.from_dict(balance_data).transpose().set_index("date")
balance = balance[['totalAssets', 'cash', 'totalCurrentAssets', 'totalCurrentLiabilities']]
financials = income.merge(balance, left_index = True, right_index = True).fillna(0)
财务数据框将如下所示(仅显示 2005-2009 年的数据):
| date | ebit | totalAssets | cash | totalCurrentAssets | totalCurrentLiabilities |
|:-----------|----------:|--------------:|-----------:|---------------------:|--------------------------:|
| 2009-12-26 | 4.758e+09 | 5.3926e+10 | 7.609e+09 | 3.3332e+10 | 1.3097e+10 |
| 2009-09-26 | 0 | 4.7501e+10 | 5.263e+09 | 3.1555e+10 | 1.1506e+10 |
| 2009-06-27 | 1.732e+09 | 4.814e+10 | 5.605e+09 | 3.517e+10 | 1.6661e+10 |
| 2009-03-31 | 0 | 4.3237e+10 | 4.466e+09 | 0 | 1.3751e+10 |
| 2008-12-31 | 0 | 4.2787e+10 | 7.236e+09 | 0 | 1.4757e+10 |
| 2008-09-30 | 0 | 3.9572e+10 | 1.1875e+10 | 0 | 1.4092e+10 |
| 2008-06-30 | 0 | 3.1709e+10 | 9.373e+09 | 0 | 9.218e+09 |
| 2008-03-31 | 0 | 3.0471e+10 | 9.07e+09 | 0 | 9.634e+09 |
| 2007-12-31 | 0 | 3.0039e+10 | 9.162e+09 | 0 | 1.0535e+10 |
| 2007-09-30 | 0 | 2.5347e+10 | 9.352e+09 | 0 | 9.299e+09 |
| 2007-06-30 | 0 | 2.1647e+10 | 7.118e+09 | 0 | 6.992e+09 |
| 2007-03-31 | 0 | 1.8711e+10 | 7.095e+09 | 0 | 5.485e+09 |
| 2006-12-31 | 0 | 1.9461e+10 | 7.159e+09 | 0 | 7.337e+09 |
| 2006-09-30 | 0 | 1.7205e+10 | 6.392e+09 | 0 | 6.471e+09 |
| 2006-06-30 | 0 | 1.5114e+10 | 0 | 0 | 5.023e+09 |
| 2006-03-31 | 0 | 1.3911e+10 | 0 | 0 | 4.456e+09 |
| 2005-12-31 | 0 | 1.4181e+10 | 0 | 0 | 5.06e+09 |
| 2005-09-30 | 0 | 1.1551e+10 | 3.491e+09 | 0 | 3.484e+09 |
| 2005-06-30 | 0 | 1.0488e+10 | 0 | 0 | 3.123e+09 |
| 2005-03-31 | 0 | 1.0111e+10 | 0 | 0 | 3.352e+09 |
content.json()['Financials']['Income_Statement']['quarterly']
是一个字典,每个键是日期,每个值是带有列数据的第二个字典。
{'2005-03-31': {'date': '2005-03-31',
'filing_date': None,
'currency_symbol': 'USD',
'researchDevelopment': '120000000.00',
...},
'2005-06-30': {...},
...}
由于是这种情况,您实际上可以通过使用将该字典直接加载到 Pandas 数据帧中
pd.DataFrame.from_dict(income_data).transpose().set_index("date")
由于 JSON 的结构,转置是必要的。 Pandas 需要一个格式为{'column name': data}
的字典。 由于键是日期,您最初将获得一个 DataFrame,其中行标记为“totalAssets”、“cash”等,列是日期。 transpose()
命令翻转行和列,使其成为您需要的格式。 最后的.set_index("date")
命令用于使用“日期”数据而不是初始关键日期,以保持一致性并命名索引。 它是完全可选的
现在,此 DataFrame 将包含 JSON 文件中的每一列,但您只对其中的几列感兴趣。 编码
income = income[['ebit']]
仅从数据中选择相关列。
由于您从两个不同的来源提取数据,因此您确实需要创建两个不同的表。 这有一个额外的好处,您可以更清楚地看到哪些列是从“损益表”中提取的,哪些列来自“资产负债表”。
最后一行
financials = income.merge(balance, left_index = True, right_index = True).fillna(0)
使用它们的索引(在本例中为“日期”列)将两个表合并在一起。 fillna(0)
确保按照您的要求将任何缺失的数据替换为零值。
如果您最终需要添加另一个表,例如“Cash_Flow”,您将使用相同的代码行来创建表并选择相关列,然后添加第二个合并行:
cashflow_data = content.json()['Financials']['Balance_Sheet']['quarterly']
cashflow = pd.DataFrame.from_dict(cashflow_data).transpose().set_index("date")
cashflow = cashflow[['accountsPayable', 'liabilitiesAndStockholdersEquity']]
...
financials.merge(cashflow, left_index = True, right_index = True).fillna(0)
作为额外提示,您的源 JSON 中有相当多的数据! 要查看任何给定表中哪些列可供您使用,请使用以下命令:
cashflow.columns.sort_values()
获取您可以使用的列的按字母顺序排列的列表:
['accountsPayable', 'accumulatedAmortization', 'accumulatedDepreciation',
'accumulatedOtherComprehensiveIncome', 'additionalPaidInCapital',
'capitalLeaseObligations', 'capitalSurpluse', 'cash',
'cashAndShortTermInvestments', 'commonStock',
'commonStockSharesOutstanding', 'commonStockTotalEquity',
'currency_symbol', 'deferredLongTermAssetCharges',
'deferredLongTermLiab', 'filing_date', 'goodWill', 'intangibleAssets',
'inventory', 'liabilitiesAndStockholdersEquity', 'longTermDebt',
'longTermDebtTotal', 'longTermInvestments', 'negativeGoodwill',
'netReceivables', 'netTangibleAssets', 'nonCurrentAssetsTotal',
'nonCurrentLiabilitiesOther', 'nonCurrentLiabilitiesTotal',
'nonCurrrentAssetsOther', 'noncontrollingInterestInConsolidatedEntity',
'otherAssets', 'otherCurrentAssets', 'otherCurrentLiab', 'otherLiab',
'otherStockholderEquity', 'preferredStockRedeemable',
'preferredStockTotalEquity', 'propertyPlantAndEquipmentGross',
'propertyPlantEquipment', 'retainedEarnings',
'retainedEarningsTotalEquity', 'shortLongTermDebt', 'shortTermDebt',
'shortTermInvestments',
'temporaryEquityRedeemableNoncontrollingInterests', 'totalAssets',
'totalCurrentAssets', 'totalCurrentLiabilities', 'totalLiab',
'totalPermanentEquity', 'totalStockholderEquity', 'treasuryStock',
'warrants']
当数据中存在拼写错误时,这也非常有用,例如上面的“capitalSurpluse”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.