pd.DataFrame.from_dict()


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

  • [ data] :字典或类似数组的对象,用来创建DataFrame。

  • [orient] :数据的方向。 允许值为(“列”,“索引”),默认值为“列”。

  • [columns ] :当方向为“索引”时,用作DataFrame标签的值的列表。 如果与列方向一起使用,则会引发ValueError 。


示例:

1. 从Dict创建DataFrame的简单示例 (Simple Example to create DataFrame from Dict)

点击查看代码
import pandas as pd
d1 = {'Name': ['Pankaj', 'Lisa'], 'ID': [1, 2]}
df = pd.DataFrame.from_dict(d1)
df

Output:

image

2. 从具有索引方向的Dict创建DataFrame (Creating DataFrame from Dict with index orientation)

点击查看代码
### 指定 orient='index'
import pandas as pd
d1 = {'Name': ['Pankaj', 'Lisa'], 'ID': [1, 2]}
df = pd.DataFrame.from_dict(d1, orient='index')
df
Output:

image

3. 将具有索引方向的Dict转换为Dict时,将标签分配给DataFrame列 (Assigning Labels to DataFrame Columns when converted Dict with index orientation)

点击查看代码
import pandas as pd
d1 = {'Name': ['Pankaj', 'Meghna'], 'ID': [1, 2], 'Role': ['CEO', 'CTO']}
df = pd.DataFrame.from_dict(d1, columns=['A', 'B'], orient='index')
df

Output:

image

我们也可以使用其构造函数将字典转换为DataFrame,但是,没有选择使用基于索引的方向。

点击查看代码
import pandas as pd
d1 = {'Name': ['Pankaj', 'Lisa'], 'ID': [1, 2]}
df = pd.DataFrame(d1)
df

Output:

image

因此,当您想要索引方向时,请使用from_dict()方法。 对于默认方案,最好使用DataFrame构造函数


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM