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