简体   繁体   中英

DataFrame.from_dict generating columns and rows Pandas python

I have this following code

df_output ={'transport':[transport],'model':[model],fuel':[fuel],'engine':[engine],'color':[color],'year':[year],'value':[value],'
number':[number],'manufacturer': [manufacturer],}

I pass df_output to be able to manipulate in DataFrame.from_dict

df = pd.DataFrame.from_dict(data=df_output, orient='index', columns=['transport', 'Model', 'Fuel', 'Engine', 'Color', 'Year', 'Value', 'Number','Manufacturer'])

i'm following the pandas documentation

he tells me to use orient = 'index' so that I can create columns manually, then I pass the columns columns=['transport', 'Model', 'Fuel', 'Engine', 'Color', 'Year', 'Value', 'Number','Manufacturer']

when i will execute my code it generates me this error

Traceback (most recent call last):
  File "C:\Users\Suporte\Desktop\Captura TJ\autonomation\Discovery.py", line 192, in <module>
    Scrape(user_tj, password_tj, pesquisa_unica)
  File "C:\Users\Suporte\Desktop\Captura TJ\autonomation\Discovery.py", line 54, in __init__
    self.single_search_csv()
  File "C:\Users\Suporte\Desktop\Captura TJ\autonomation\Discovery.py", line 182, in single_search_csv
    df = pd.DataFrame.from_dict(data=df_output, orient='index', columns=['transport', 'Model', 'Fuel', 'Engine', 'Color', 'Year', 'Value', 'Number','Manufacturer'])
  File "C:\Users\Suporte\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\frame.py", line 1190, in from_dict
    return cls(data, index=index, columns=columns, dtype=dtype)
  File "C:\Users\Suporte\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\frame.py", line 450, in __init__
    arrays, columns = to_arrays(data, columns, dtype=dtype)
  File "C:\Users\Suporte\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\internals\construction.py", line 464, in to_arrays
    return _list_to_arrays(data, columns, coerce_float=coerce_float, dtype=dtype)
  File "C:\Users\Suporte\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\internals\construction.py", line 503, in _list_to_arrays
    raise ValueError(e) from e
ValueError: 9 columns passed, passed data had 1 columns

after everything goes well i will generate a csv

df.to_csv('file.csv', sep = ';', encoding = 'iso-8859-1', mode='a', index=False )

who can help me thank you:)

When you create df_output , drop square brackets surrounding each value.

I assume that transport , model and so on are lists. The way you initially wrote, you unnecessarily create another set of lists, each containg only one element (a list).

So change the instruction to:

df_output = {'transport': transport, 'model': model, ...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM