我有以下数据框:

    Date       Blue     Red      Green
-----------------------------------------
1   1/1/14       55      34         34  
2   1/2/14       36      35         23 
3   1/3/14       23      46         43
4   1/4/14       47      34         55

我想将这些具有唯一值的以 colored颜色 命名的列"堆叠"到一个单独的" colored颜色 "列中,每个列都有相应的属性值,这样就有三个列,每一行有一个日期(按时间顺序、一个 colored颜色 标签和属性值),每种 colored颜色 的日期都重复.

因此,我正在try 获取以下数据帧:

       Date       Color
--------------------------
 1   1/1/14        Blue
 2   1/2/14        Blue
 3   1/3/14        Blue
 4   1/4/14        Blue
 5   1/1/14         Red
 6   1/2/14         Red
 7   1/3/14         Red
 8   1/4/14         Red
 9   1/1/14       Green
10   1/2/14       Green
11   1/3/14       Green
12   1/4/14       Green
------------------------

我正在try 按 colored颜色 "堆叠"我的列,但我不确定我应该堆叠、融化还是连接.我应该使用哪种方法将我的所有 colored颜色 及其值放入一列?

推荐答案

我正在try 按 colored颜色 "堆叠"我的列,但我不确定我应该堆叠、融化还是连接.

使用melt:

>>> df.melt(id_vars='Date', var_name='Color', value_name='Value')
      Date  Color  Value
0   1/1/14   Blue     55
1   1/2/14   Blue     36
2   1/3/14   Blue     23
3   1/4/14   Blue     47
4   1/1/14    Red     34
5   1/2/14    Red     35
6   1/3/14    Red     46
7   1/4/14    Red     34
8   1/1/14  Green     34
9   1/2/14  Green     23
10  1/3/14  Green     43
11  1/4/14  Green     55

具有不同输出的替代方案:

>>> (df.set_index('Date').stack()
       .rename_axis(['Date', 'Color'])
       .reset_index(name='Value'))
      Date  Color  Value
0   1/1/14   Blue     55
1   1/1/14    Red     34
2   1/1/14  Green     34
3   1/2/14   Blue     36
4   1/2/14    Red     35
5   1/2/14  Green     23
6   1/3/14   Blue     23
7   1/3/14    Red     46
8   1/3/14  Green     43
9   1/4/14   Blue     47
10  1/4/14    Red     34
11  1/4/14  Green     55

Python相关问答推荐

Inquirer库不适用于Pyterfly

使用Python进行网页抓取,没有页面

为什么我的(工作)代码(生成交互式情节)在将其放入函数中时不再工作?

为什么基于条件的过滤会导致pandas中的空数据框架?

计算相同形状的两个张量的SSE损失

Chatgpt API不断返回错误:404未能从API获取响应

如何调整spaCy token 化器,以便在德国模型中将数字拆分为行末端的点

如何在图片中找到这个化学测试条?OpenCV精明边缘检测不会绘制边界框

Pydantic 2.7.0模型接受字符串日期时间或无

acme错误-Veritas错误:模块收件箱没有属性linear_util'

对整个 pyramid 进行分组与对 pyramid 列子集进行分组

类型错误:输入类型不支持ufuncisnan-在执行Mann-Whitney U测试时[SOLVED]

如何避免Chained when/then分配中的Mypy不兼容类型警告?

Excel图表-使用openpyxl更改水平轴与Y轴相交的位置(Python)

如何过滤包含2个指定子字符串的收件箱列名?

Python—从np.array中 Select 复杂的列子集

在嵌套span下的span中擦除信息

为什么\b在这个正则表达式中不解释为反斜杠

在Python中调用变量(特别是Tkinter)

(Python/Pandas)基于列中非缺失值的子集DataFrame