You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Pandas DataFrame中的所有数据合并为一个Series?

将Pandas DataFrame的所有列数据整合为单个Series

方法一:使用stack()(推荐,更简洁)

先构造示例DataFrame:

import pandas as pd

df = pd.DataFrame({
    'Fruits': ['Apple', 'Banana', 'Pear'],
    'Vegetables': ['Spinach', 'Cucumber', 'Carrot'],
    'Protein': ['Beef', 'Chicken', 'Pork']
}, index=[1,2,3])

执行以下代码即可得到目标格式的Series:

# 堆叠列数据、重置索引、设置名称
all_foods = df.stack().reset_index(drop=True).rename('All Foods')
# 调整索引从1开始(匹配示例输出)
all_foods.index = all_foods.index + 1

步骤说明:

  • df.stack():把DataFrame的每一列数据依次堆叠,生成带多层索引的Series,每个单元格的值都成为独立元素。
  • reset_index(drop=True):移除堆叠产生的多层索引,生成连续的整数索引。
  • rename('All Foods'):为Series设置名称,对应目标格式的列标题。
  • 最后一行将索引从默认的0起始改为1起始,和示例输出完全匹配。

方法二:使用melt()

如果习惯用宽表转长表的思路,也可以用melt()实现:

all_foods = df.melt(value_name='All Foods')['All Foods']
all_foods.index = all_foods.index + 1

melt()会将所有列转换为"变量-值"的结构,我们直接提取值列即可,后续同样调整索引。

最终输出效果

执行后得到的all_foods Series如下:

1       Apple
2      Banana
3        Pear
4      Spinach
5    Cucumber
6       Carrot
7        Beef
8      Chicken
9         Pork
Name: All Foods, dtype: object

内容的提问来源于stack exchange,提问作者ehkhacha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:55:18