Python 将 Series 索引转换为 DataFrame 列
使用 reset_index() 方法可以将 Series 的索引作为一列,并生成一个两列的数据框。
以下是一个示例代码:
import pandas as pd
# 创建一个 Series
data = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
# 将 Series 的索引作为一列,并生成一个两列的数据框
df = data.reset_index()
# 打印数据框
print(df)
输出结果:
index 0
0 a 1
1 b 2
2 c 3
3 d 4
在上面的示例中,reset_index() 方法将 Series 的索引作为一个名为 'index' 的列添加到数据框中,并将原来的数据作为第二列。
原文地址: https://www.cveoy.top/t/topic/qzCu 著作权归作者所有。请勿转载和采集!