Series.reset_index
with name
argumentOften the use case comes up where a Series needs to be promoted to a DataFrame. But if the Series has no name, then reset_index
will result in something like,
s = pd.Series([1, 2, 3], index=['a', 'b', 'c']).rename_axis('A')
s
A
a 1
b 2
c 3
dtype: int64
s.reset_index()
A 0
0 a 1
1 b 2
2 c 3
Where you see the column name is "0". We can fix this be specifying a name
parameter.
s.reset_index(name='B')
A B
0 a 1
1 b 2
2 c 3
s.reset_index(name='list')
A list
0 a 1
1 b 2
2 c 3
Series.to_frame
If you want to create a DataFrame without promoting the index to a column, use Series.to_frame
, as suggested in this answer. This also supports a name parameter.
s.to_frame(name='B')
B
A
a 1
b 2
c 3
pd.DataFrame
ConstructorYou can also do the same thing as Series.to_frame
by specifying a columns
param:
pd.DataFrame(s, columns=['B'])
B
A
a 1
b 2
c 3