简体   繁体   English

如何在将dict键设为第一列而不是索引的同时,从字典转到pandas DataFrame再到CSV

[英]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 我有一个列表字典,可以将其转换为pandas DataFrame
  2. I write that DataFrame to a CSV 我将DataFrame写入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'). 我希望字典的是DataFrame的第一列而不是index ,因为我需要这些值具有列名('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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在将 dict 转换为 pandas DataFrame 时设置列标题(其中列名与 dict 键不匹配)? - How to set column headers while converting dict to pandas DataFrame (where column names do not match dict keys)? 从嵌套dict创建pandas数据帧,外键为df索引和内键列标题 - Create pandas dataframe from nested dict with outer keys as df index and inner keys column headers 从字典创建数据框的最佳方法是什么,其中字典键是元组:(索引,列)? - What would be the best way of creating a dataframe from dictionary, where dict keys are tuples: (index, column)? 从dict制作熊猫数据框 - Making pandas dataframe from dict 如何使用键作为列和行索引从字典构造pandas DataFrame - How to construct pandas DataFrame from dictionary with key as column and row index Pandas 将 dataframe 转换为具有唯一键的字典作为(索引,列)来自 dataframe - Pandas convert dataframe to dictionary with unique keys as (index,col) from the dataframe 熊猫和字典:将Dict转换为DataFrame并将值中的内部键用作DataFrame列标题 - Pandas and Dictionary: Convert Dict to DataFrame and use inner keys in values as DataFrame column headers 将字典值增量添加到pandas DataFrame。 具有dict键的列名称的DataFrame - Incremental addition of dictionary values to a pandas DataFrame. DataFrame with column names of dict keys Pandas:当键是数据帧的索引时,从字典向数据帧添加列 - Pandas: adding a column to a dataframe from dictionary, when keys are the indices of the dataframe 如何使用字典中的键作为索引创建 pandas DataFrame? [蟒蛇,熊猫] - How can I create a pandas DataFrame with keys from a dictionary as my index? [Python, pandas]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM