看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
pandas to_frame() 把一维的 Series 转成二维的 DataFrame,方便后续做列拼接、SQL 写入、机器学习特征矩阵等需要「表结构」的操作。
只要是 pandas.Series 就可以调用,跟 Series 里存的是数字、字符串、布尔、datetime、category 等无关。
语法(参数只有 1 个,无需换行):
DataFrame = Series.to_frame(name=None)
参数说明:
返回值:
一个只有一列的 pandas.DataFrame,索引与原来的 Series 完全一致。
由浅入深的 4 个使用场景与示例。把 Series 变成 DataFrame,方便 concat 横向拼接:
import pandas as pd
# 构造示例数据
s = pd.Series([10, 20, 30], name='score')
print("原始 Series:")
print(s)
df = s.to_frame() # 沿用原名 'score'
print("\nto_frame 后:")
print(df)
"""
输出对照:
原始 Series:
0 10
1 20
2 30
Name: score, dtype: int64
to_frame 后:
score
0 10
1 20
2 30
"""
原 Series 没有名字,用 name 参数主动给列命名:
s2 = pd.Series(['男', '女', '女']) # 注意这里没有 name
df2 = s2.to_frame(name='性别')
print("\n原 Series 无名字,to_frame 指定 name:")
print(df2)
"""
输出:
性别
0 男
1 女
2 女
"""
在链式调用里快速生成 DataFrame,再接着做列运算:
df3 = (pd.Series([1, 2, 3, 4])
.to_frame('x')
.assign(y=lambda d: d.x * 2) # 新增一列 y
)
print("\n链式调用示例:")
print(df3)
"""
输出:
x y
0 1 2
1 2 4
2 3 6
3 4 8
"""
把多个 Series 分别 to_frame 后再 concat,拼成宽表:
s4_height = pd.Series([168, 172, 165], name='height')
s4_weight = pd.Series([65, 70, 58], name='weight')
big_df = pd.concat([s4_height.to_frame(),
s4_weight.to_frame()], axis=1)
print("\n多 Series 拼成宽表:")
print(big_df)
"""
输出:
height weight
0 168 65
1 172 70
2 165 58
"""
(完)
更新时间:2025-09-11 08:52:35 标签:pandas python frame