freshman_2021
freshman_2021

Reputation: 371

convert series to dataframe and rename

I have a series that looks as as below

Col 
0.006325    1
0.050226    2
0.056898    2
0.075840    2
0.089026    2
0.099637    1
0.115992    1
0.129045    1
0.148997    1
0.164790    2
0.188730    5
0.207524    3
0.235777    1

I want to create a df that looks like

Col         Frequency
0.006325    1
0.050226    2
0.056898    2
0.075840    2
0.089026    2
0.099637    1

I have tried series.reset_index().rename(columns={'col','frequency'}) with no success.

Upvotes: 0

Views: 184

Answers (2)

SeaBean
SeaBean

Reputation: 23217

Try to use the name= parameter of Series.reset_index(), as follows:

df = series.reset_index(name='frequency')

Demo

data = {0.006325: 1,
 0.050226: 2,
 0.056898: 2,
 0.07584: 2,
 0.089026: 2,
 0.099637: 1,
 0.115992: 1,
 0.129045: 1,
 0.148997: 1,
 0.16479: 2,
 0.18873: 5,
 0.207524: 3,
 0.235777: 1}

series = pd.Series(data).rename_axis(index='Col')

print(series)

Col
0.006325    1
0.050226    2
0.056898    2
0.075840    2
0.089026    2
0.099637    1
0.115992    1
0.129045    1
0.148997    1
0.164790    2
0.188730    5
0.207524    3
0.235777    1
dtype: int64

df = series.reset_index(name='frequency')

print(df)

         Col  frequency
0   0.006325          1
1   0.050226          2
2   0.056898          2
3   0.075840          2
4   0.089026          2
5   0.099637          1
6   0.115992          1
7   0.129045          1
8   0.148997          1
9   0.164790          2
10  0.188730          5
11  0.207524          3
12  0.235777          1

Upvotes: 1

Michael S.
Michael S.

Reputation: 337

I can think of two pretty sensible options.

pd_series = pd.Series(range(5), name='series')

# Option 1
# Rename the series and convert to dataframe
pd_df1 = pd.DataFrame(pd_series.rename('Frequency'))

# Option 2
# Pass the series in a dictionary
# the key in the dictionary will be the column name in dataframe
pd_df2 = pd.DataFrame(data={'Frequency': pd_series})

Upvotes: 0

Related Questions