有没有办法从字典中提取数据到csv文件

时间:2021-06-19 19:25:02

标签: python csv dictionary

下面的代码会将多个股票数据放入字典。但我需要将它们放入单个 csv 文件

代码:

import pandas as pd
from datetime import datetime as dt
from nsepy import get_history

stocks = ['JSWSTEEL','RELIANCE','AXISBANK','HCLTECH','TECHM']
df = {}
for tickers in stocks:
    df[tickers] = get_history(tickers,dt(2020,1,1),dt(2021,1,1))

1 个答案:

答案 0 :(得分:0)

使用pandas从字典中创建一个DataFrame,然后像这样使用pandas.to_csv()函数:

import pandas as pd
from datetime import datetime as dt
from nsepy import get_history

stocks = ['JSWSTEEL','RELIANCE','AXISBANK','HCLTECH','TECHM']
df = {}
for tickers in stocks:
    df[tickers] = get_history(tickers,dt(2020,1,1),dt(2021,1,1))

dataset = pd.DataFrame([df], index=[0])
csv_data = dataset.to_csv("your_file_path.csv")

效果很好!