Its output
is as follows −
Age Name
rank1 28 Tom
rank2 34 Jack
rank3 29 Steve
rank4 42 Ricky
Note
− Observe, the index
parameter assigns an index to each row.
Create a DataFrame from List of Dicts:
List of Dictionaries can be passed as input data to create a DataFrame. The dictionary keys are by default taken as column names.
Example 1:
The following example shows how to create a DataFrame by passing a list of dictionaries.
import
pandas as
pd
data =
[{
'a'
:
1
,
'b'
:
2
},{
'a'
:
5
,
'b'
:
10
,
'c'
:
20
}]
df =
pd.
DataFrame
(
data)
print
df
Its output
is as follows −
a b c
0 1 2 NaN
1 5 10 20.0
Note
− Observe, NaN (Not a Number) is appended in missing areas.
Example 2:
The following example shows how to create a DataFrame by passing
a list of dictionaries and the row indices.
import
pandas as
pd
data =
[{
'a'
:
1
,
'b'
:
2
},{
'a'
:
5
,
'b'
:
10
,
'c'
:
20
}]
df =
pd.
DataFrame
(
data,
index=[
'first'
,
'second'
])
print
df
Its output
is as follows −
a b c
first 1 2 NaN
second 5 10 20.0
Example 3:
The following example shows how to create a DataFrame with a list of dictionaries, row indices, and column indices.
import
pandas as
pd
data =
[{
'a'
:
1
,
'b'
:
2
},{
'a'
:
5
,
'b'
:
10
,
'c'
:
20
}]
#With two column indices, values same as dictionary keys
df1 =
pd.
DataFrame
(
data,
index=[
'first'
,
'second'
],
columns=[
'a'
,
'b'
])
#With two column indices with one index with other name
df2 =
pd.
DataFrame
(
data,
index=[
'first'
,
'second'
],
columns=[
'a'
,
'b1'
])
print
df1
print
df2
Its output
is as follows −
#df1 output
a b
first 1 2
second 5 10
a b1
first 1 NaN
second 5 NaN
Note
− Observe, df2 DataFrame is created with a column index other than the dictionary key; thus, appended the NaN’s in place. Whereas, df1 is created with column indices same as dictionary keys, so NaN’s appended.
Create a DataFrame from Dict of Series:
Dictionary of Series can be passed to form a DataFrame. The resultant index is the union of all the series indexes passed.