python - Pandas reshape 重复行

标签 python pandas

我想 reshape 具有重复行的数据框。数据来自 csv 文件,其中重复数据 block 。

举个例子:

    Name      1st    2nd
0 Value1      a1     b1 
1 Value2      a2     b2 
2 Value3      a3     b3
3 Value1      a4     b4
4 Value2      a5     b5
5 Value3      a6     b6

应 reshape 为:

Name     1st 2nd 3rd 4th
Value1   a1  b1  a4  b4
Value2   a2  b2  a5  b5
Value3   a3  b3  a6  b6

您对如何做到这一点有什么建议吗? 我已经看过这个thread ,但是我不知道如何将这种方法转化为我的问题,因为在 groupby 所在的列右侧有多个列。

最佳答案

您可以使用set_indexstack将两列合并为一列,cumcount获取新的列标签,以及 pivot进行 reshape :

# Stack the 1st and 2nd columns, and use cumcount to get the new column labels.
df = df.set_index('Name').stack().reset_index(level=1, drop=True).to_frame()
df['new_col'] = df.groupby(level='Name').cumcount()

# Perform a pivot to get the desired shape.
df = df.pivot(columns='new_col', values=0)

# Formatting.
df = df.reset_index().rename_axis(None, 1)

结果输出:

     Name   0   1   2   3
0  Value1  a1  b1  a4  b4
1  Value2  a2  b2  a5  b5
2  Value3  a3  b3  a6  b6

关于python - Pandas reshape 重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43595091/

相关文章:

python - 帮助错误信息

python - 用重复值填充 nan

python - google-chrome 无法在 flask 应用程序中以 Selenium 开头

python - 有没有一种 pythonic 方法来获取可迭代中相同值的簇的开始和结束索引?

Python Pandas - 使用时间戳定位器和偏移量检索行

python - 更新行的替代方法

python - 当需要窗口中多列的所有变量时如何应用滚动函数

python - 使用整数映射 Pandas Dataframe 中的字符串值

python - 在 CNTLM 代理后面使用 pip

Python - 日期时间没有正确计算闰秒?