pandas.DataFrame.from_dict直接从字典构建DataFrame

本文详细介绍了如何使用pandas的DataFrame.from_dict()方法将字典转换为DataFrame。默认情况下,字典的键成为DataFrame的列,而设置orient='index'则使键成为行。同时,我们可以指定列名来定制DataFrame的结构。示例展示了不同参数设置下的DataFrame创建过程。

pandas函数中pandas.DataFrame.from_dict 直接从字典构建DataFrame 。

参数解析

DataFrame from_dict()方法用于将Dict转换为DataFrame对象。 此方法接受以下参数。

  • data: dict or array like object to create DataFrame.data :字典或类似数组的对象来创建DataFrame。
  • orient: The orientation of the data. The allowed values are (‘columns’, ‘index’), default is the ‘columns’.  orient :数据的方向。 允许值为(“列”,“索引”),默认值为“列”。 Specify orient='index' to create the DataFrame using dictionary keys as rows:。 当参数orient为index值时,会将字典的keys作为DataFrame的行。(默认是keys变为列)
  • columns: a list of values to use as labels for the DataFrame when orientation is ‘index’. If it’s used with columns orientation, ValueError is raised.     columns :当方向为“索引”时,用作DataFrame标签的值的列表。 如果与列方向一起使用,则会引发ValueError 。

实例  

1)By default the keys of the dict become the DataFrame columns:

默认是将字典的keys作为列

data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}
pd.DataFrame.from_dict(data)
   col_1 col_2
0      3     a
1      2     b
2      1     c
3      0     d

2) Specify orient='index' to create the DataFrame using dictionary keys as rows: 参数orient为index值时,会将字典的keys作为DataFrame的行

data = {'row_1': [3, 2, 1, 0], 'row_2': ['a', 'b', 'c', 'd']}
pd.DataFrame.from_dict(data, orient='index')
       0  1  2  3
row_1  3  2  1  0
row_2  a  b  c  d

3) orient为index值时, 可以手动命名列名

pd.DataFrame.from_dict(data, orient='index',
                       columns=['A', 'B', 'C', 'D'])
       A  B  C  D
row_1  3  2  1  0
row_2  a  b  c  d

参考: pandas.DataFrame.from_dict — pandas 1.3.4 documentation

`pandas.DataFrame.from_dict()` 是一个非常常用的从字典创建 DataFrame 的方法。你提到的两个需求: 1. **不使用索引列(即不把字典的键作为行索引)** 2. **给索引列命名** 我们来逐一解释并提供代码示例。 --- ### ✅ 1. `from_dict()` 默认行为回顾 默认情况下,`from_dict()` 把字典的 **键** 当作 **列名**,而 **值** 的长度决定行数,**行索引自动生成为 `0, 1, 2, ...`**。 ```python import pandas as pd data = { '姓名': ['张三', '李四'], '年龄': [25, 30] } df = pd.DataFrame.from_dict(data) print(df) ``` 输出: ``` 姓名 年龄 0 张三 25 1 李四 30 ``` ✅ 这时候索引是 `0, 1`,没有名字,类型是 `RangeIndex`。 --- ## 🌟 目标一:给索引列命名 虽然索引不是“普通列”,但你可以为它设置一个名字,这样在保存为 CSV 或展示时更清晰。 ### ✅ 方法:使用 `.index.name` ```python df.index.name = 'ID' print(df) ``` 输出: ``` 姓名 年龄 ID 0 张三 25 1 李四 30 ``` 如果你导出到 CSV: ```python df.to_csv('output.csv') ``` CSV 文件第一列会是 `ID`,然后是 `姓名`, `年龄`。 > 🔔 注意:这个 `ID` 是索引的名字,不是普通列。 --- ### ✅ 更进一步:将索引变成普通列(去掉索引列) 如果你**不想用索引列**,而是希望所有数据都是“普通列”,可以调用 `.reset_index()`。 ```python df.index.name = 'ID' df = df.reset_index() # 把索引变成普通列 print(df) ``` 输出: ``` ID 姓名 年龄 0 0 张三 25 1 1 李四 30 ``` 现在 `ID` 是一个真正的列了。 --- ## 🌟 目标二:控制 from_dict() 的 orient 参数(高级用法) `from_dict()` 有一个参数叫 `orient`,默认是 `'columns'`,表示字典的外层键是列名。 但如果你设置 `orient='index'`,则外层键会变成**行索引**! ### ❌ 错误示例(可能导致你不想要的索引) ```python data = { 'person1': {'姓名': '张三', '年龄': 25}, 'person2': {'姓名': '李四', '年龄': 30} } df = pd.DataFrame.from_dict(data, orient='index') print(df) ``` 输出: ``` 姓名 年龄 person1 张三 25 person2 李四 30 ``` 👉 这时候 `'person1'`, `'person2'` 成了行索引! --- ### ✅ 如何避免?或如何命名这个索引? #### 方案 A:保留索引,并命名它 ```python df = pd.DataFrame.from_dict(data, orient='index') df.index.name = 'PersonID' print(df) ``` 输出: ``` 姓名 年龄 PersonID person1 张三 25 person2 李四 30 ``` #### 方案 B:把索引转为普通列(推荐) ```python df = pd.DataFrame.from_dict(data, orient='index').reset_index() df.rename(columns={'index': 'PersonID'}, inplace=True) # 可选:重命名生成的列 print(df) ``` 输出: ``` PersonID 姓名 年龄 0 person1 张三 25 1 person2 李四 30 ``` --- ## ✅ 总结:常见模式模板 ### 模板 1:标准用法(无需改索引) ```python df = pd.DataFrame.from_dict({ '姓名': ['张三', '李四'], '年龄': [25, 30] }) df.index.name = 'ID' # 给索引命名 ``` ### 模板 2:字典按行组织 → 转成 DataFrame 并命名索引 ```python data = { 'p1': {'姓名': '张三', '年龄': 25}, 'p2': {'姓名': '李四', '年龄': 30} } df = pd.DataFrame.from_dict(data, orient='index') df.index.name = 'PersonID' df = df.reset_index() # 转为普通列 ``` --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值