熊猫DataFrame from_dict()–字典到DataFrame

Pandas DataFrame from_dict() method is used to convert Dict to DataFrame object. This method accepts the following parameters.

熊猫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 :数据的方向。 允许值为(“列”,“索引”),默认值为“列”。
  • 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

Pandas DataFrame from_dict()示例 (Pandas DataFrame from_dict() Examples)

Let’s look at some examples to convert dict to DataFrame object.

让我们看一些将dict转换为DataFrame对象的示例。

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

import pandas as pd

d1 = {'Name': ['Pankaj', 'Lisa'], 'ID': [1, 2]}

df = pd.DataFrame.from_dict(d1)

print(df)

Output:

输出:

Name  ID
0  Pankaj   1
1    Lisa   2

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

import pandas as pd

d1 = {'Name': ['Pankaj', 'Lisa'], 'ID': [1, 2]}

df = pd.DataFrame.from_dict(d1, orient='index')

print(df)

Output:

输出:

0     1
Name  Pankaj  Lisa
ID         1     2

3.将具有索引方向的Dict转换为Dict时,将标签分配给DataFrame列 (3. 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')

print(df)

Output:

输出:

A       B
Name  Pankaj  Meghna
ID         1       2
Role     CEO     CTO

什么时候使用DataFrame from_dict()方法? (When to use DataFrame from_dict() method?)

We can convert dictionary to DataFrame using its constructor too.

我们也可以使用其构造函数将字典转换为DataFrame。

import pandas as pd

d1 = {'Name': ['Pankaj', 'Lisa'], 'ID': [1, 2]}

df = pd.DataFrame(d1)
print(df)

Output:

输出:

Name  ID
0  Pankaj   1
1    Lisa   2

But, there is no option to use index-based orientation.

但是,没有选择使用基于索引的方向。

So, when you want index orientation, use from_dict() method. For default scenarios, you are better off with the DataFrame constructor.

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

参考资料 (References)

翻译自: https://www.journaldev.com/33472/pandas-dataframe-from_dict-convert-dictionary-to-dataframe

  • 4
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值