简体   繁体   中英

How to go from dictionary to pandas DataFrame to CSV while making the dict keys the first column, not the index

  1. I have a dictionary of lists that I convert into a pandas DataFrame
  2. I write that DataFrame to a CSV

I want the keys of the dictionary to be the first column of the DataFrame, not the index , because I need those values to have a column name ('ID'). I cannot for the life of me figure out how to make that happen.

Here is my code:

import pandas as pd 

df = pd.DataFrame.from_dict(dict_name, orient='index', columns = ['A', 'B', 'C', 'D', 'E'])

df.to_csv('output_filename', sep='\t')

Reset the index then don't include the newly generated sequential index in the file:

df.index.names = ['ID']
df.reset_index().to_csv('output_filename', sep='\t', index=False)

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