Home > other >  AttributeError: 'Pandas' object has no attribute 'to_dict'
AttributeError: 'Pandas' object has no attribute 'to_dict'

Time:07-06

I am trying to convert a tuple of a Pandas DataFrame into a dictionary because I need the dict to call an API later. I have an entire Dataframe, from which I iterate a for loop to get all data inside it. Here is the code

df = ....Dataframe definition and retriving

            for item in df.itertuples():
                print(item.to_dict)

But the following error appears: AttributeError: 'Pandas' object has no attribute 'to_dict'

I have also tried using the dict keyword to convert the tuple, but there is the following error:cannot convert dictionary update sequence element #0 to a sequence

I know that I could do almost everything manually, but it would be two for loop and it will take forever. Is there a way to convert the structure I have into a dict, also based on the columns? Thank you so much

CodePudding user response:

df.to_dict()

is a method that you call and by different arguments you can get:

‘list’ : dict like {column -> [values]}

‘series’ : dict like {column -> Series(values)}

‘split’ : dict like {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}

See the [docs][1].

And if you have only one dataframe, you can use this method without itertuples. [1]: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html

  • Related