1

Need to convert a dictionary to DataFrame in python. My current attempt and error

I understand I cannot use Scalar values but the dictionary is getting picked up directly from Yahoo finance API and I need all of that data to be put into a DataFrame but if I do a direct Signal_data = pd.DataFrame - it skips the Stock name which is important.

Is there any way to directly convert the entire signal_data into a DataFrame including the Stock Name which is UPL.NS and INFY.NS and the date.

  • The issue is solved - Working code that helped me : - tickerStrings = ["UPL.NS","INFY.NS",] df = yf.download(tickerStrings, group_by='Ticker', period='2d') df = df.stack(level=0).rename_axis(['Date', 'Ticker']).reset_index(level=1) – Yash Kasera Jan 31 '22 at 15:09

2 Answers2

1

Are you using the yfinance package? If so there is detailed discussion in the following thread on how to correctly read in multiple stocks:

How to deal with multi-level column names downloaded with yfinance

0

The error of the code you posted is about the index=[0] argument you pass when you construct the DataFrame.

From the official pandas documentation site, for creating a DataFrame from a Python dict, there is no index argument in the DataFrame construction. Try to create the DataFrame according to the Pandas site, and report any problems with a code sample.

Regards

exch_cmmnt_memb
  • 173
  • 1
  • 13
  • I tried it without index = [0] as well. the following code : - print(type(signal_data)) print(signal_data) new = pd.DataFrame.from_dict(signal_data) The error : ValueError: If using all scalar values, you must pass an index – Yash Kasera Jan 31 '22 at 14:47
  • signal_data = {} ticker = ["UPL.NS","INFY.NS",] df_list = list() my_df_daily = pd.DataFrame() for i in ticker: signal_data[i] = yf.download(i,list_date[0],list_date[1],interval = "1D") signal_data['ticker'] = i df_list.append(signal_data) df = pd.concat(df_list) – Yash Kasera Jan 31 '22 at 15:00
  • The second comment is my current running code. I am sorry for the spacing not sure how to add it on here. But this current code gives an error @ df = pd.concat(df_list) - TypeError: cannot concatenate object of type ''; only Series and DataFrame objs are valid – Yash Kasera Jan 31 '22 at 15:02
  • I do not know why that error is there because df_list is clearly a list so I am not sure what the problem is. Again sorry for the shabby way the code is getting displayed on here – Yash Kasera Jan 31 '22 at 15:02
  • The error says that `df_list` is of type `dict`. The `df = pd.concat(df_list)` works between Series and DataFrames. You have to make the dictionary a DataFrame before concatenating. – exch_cmmnt_memb Jan 31 '22 at 18:02