如何将字典转换为含索引、键、值三列的DataFrame?
解决方案
你可以通过两种方式实现目标结构:
方法1:直接用字典项构造DataFrame
把字典的键值对转换成元组列表,直接传入pd.DataFrame并指定列名,会自动生成从0开始的索引:
import pandas as pd from pathlib import Path, PureWindowsPath def build_failmacro_df() -> pd.DataFrame: """build a dataframe containing sites with failing macros""" sites = get_failing_sites() # 返回的字典格式如 {'StringAwesome': PureWindowsPath('//server/cool.log'), ...} # 用字典的items()方法获取键值对元组,指定列名 df = pd.DataFrame(sites.items(), columns=['columnA', 'columnB']) df.to_csv(Path(r'C:\test.csv'), index=True) # index=True保留默认索引列 return df build_failmacro_df()
方法2:基于现有代码调整
如果想保留from_dict的用法,可先按orient='index'生成DataFrame,再重置索引并重命名列:
import pandas as pd from pathlib import Path, PureWindowsPath def build_failmacro_df() -> pd.DataFrame: """build a dataframe containing sites with failing macros""" sites = get_failing_sites() # 用orient='index'生成,指定列名为columnB df = pd.DataFrame.from_dict(sites, orient='index', columns=['columnB']) # 重置索引,将原索引(字典的键)转为columnA列,生成新的默认索引 df = df.reset_index().rename(columns={'index': 'columnA'}) df.to_csv(Path(r'C:\test.csv'), index=True) return df build_failmacro_df()
说明:
- 两种方法最终都会生成你需要的结构:默认整型索引(从0开始)、
columnA列存储字典的键、columnB列存储对应的PureWindowsPath值。 - 导出CSV时
index=True会保留索引列,完全匹配index -- columnA -- columnB的格式。 PureWindowsPath对象在导出CSV时会自动转为字符串格式,无需额外处理。
内容的提问来源于stack exchange,提问作者LifeMy333
相关产品推荐
相关产品推荐

