看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)运营部三张报表:
import pandas as pd
# 1) 1×1 DataFrame → 0D 标量
gmv_total = pd.DataFrame({'8月总GMV': [1234.5]})
# 2) 10×1 DataFrame → 1D Series
gmv_daily = pd.DataFrame(
{'GMV': [110, 120, 95, 105, 115, 130, 125, 100, 108, 125]}
)
# 3) 单值 Series → 0D 标量
single_val = pd.Series([88.8], name='昨日GMV')
用 一行 squeeze()
分别完成:
gmv_total
→ 标量gmv_daily
→ Seriessingle_val
→ 标量并打印结果与类型。
代码如下:
total_scalar = gmv_total.squeeze()
daily_series = gmv_daily.squeeze()
single_scalar = single_val.squeeze()
print("总GMV标量:", total_scalar, type(total_scalar))
print("每日GMV Series:\n", daily_series, type(daily_series))
print("昨日GMV标量:", single_scalar, type(single_scalar))
输出示例:
总GMV标量: 1234.5 <class 'numpy.float64'>
每日GMV Series:
0 110
1 120
2 95
3 105
4 115
5 130
6 125
7 100
8 108
9 125
Name: GMV, dtype: int64 <class 'pandas.core.series.Series'>
昨日GMV标量: 88.8 <class 'numpy.float64'>
(完)
更新时间:2025-08-21 20:52:38 标签:pandas python squeeze 压缩 降维