将系列转换为数据框并重命名

convert series to dataframe and rename

我有一个系列如下所示

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

我想创建一个看起来像

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

我试过series.reset_index().rename(columns={'col','frequency'})没有成功。

尝试使用Series.reset_index()name=参数,如下:

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

演示

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

我可以想到两个非常明智的选择。

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})