dataframe每一行是dict或者list的巢狀,展開的方式
阿新 • • 發佈:2020-12-16
技術標籤:python資料處理技巧python
掘金成分股的原始資料格式
constituents trade_date
{'SHSE.600527': 0.009999999776482582, 'SHSE.600461': 0.019999999552965164,···} 2017-07-31 00:00:00
{'SHSE.603966': 0.009999999776482582, 'SHSE.603960': 0.009999999776482582,···} 2017-08-31 00:00:00
···
我想要的資料格式
stockcode
2016-01-29 SZSE.300002
2016-01-29 SZSE.300003
2016-01-29 SZSE.000568
2016-01-29 SZSE.000623
2016-01-29 SHSE.600398
...
2020-11-30 SHSE.600297
2020-11-30 SHSE.600352
2020-11-30 SHSE.600299
2020-11-30 SHSE.600406
2020-11-30 SHSE.600362
[17700 rows x 1 columns]
弄了好一會,記錄一下,方便下次用到
stock300 = get_history_constituents(index='SHSE.000300', start_date='2016-01-01', end_date='2020-12-01')#[0]['constituents']
df300=pd.DataFrame(stock300)
df_300=df300.constituents.apply(lambda x:list(x.keys()))#.iloc[:,1]
df_300.index=df300.trade_date
#列表展開 然後每個列表再做成df,
list300=df_300. values.flatten()
indexs=list(map(lambda x:x.date(),df_300.index))
#時間索引為成分股數量的長度
listdf_300=list(map(lambda x,y:pd.DataFrame(x,index=[y]*len(x),columns=['stockcode']),list300,indexs))
#list巢狀df的合併
df_=reduce(lambda x,y:pd.concat([x,y]),listdf_300)
print(df_)
df_.to_csv('stock300.csv')#,index=False