python - 部分取消透视 pandas DataFrame

标签 python pandas dataframe pivot-table

我有下表 DataFrame

<表类=“s-表”> <标题> 项目 描述 存储 1 数量 存储 1 个值 存储 2 数量 存储 2 个值 <正文> 项目 1 一些项目名称 5 120 7 240 第 2 项 其他一些项目 9 1234 12 98

Python 上有没有简单的方法来仅取消透视存储? 要做到这一点:

<表类=“s-表”> <标题> 项目 描述 商店编号 值 数量 <正文> 项目 1 一些项目名称 商店 1 5 120

我正在考虑将其完全取消旋转,然后将其旋转回来,保留值(value)和数量作为值。但我认为应该有一些更有效的解决方案

最佳答案

如果需要Qty, Value来分隔列,请将第一列转换为MultiIndex,因此可以使用Series.str.rsplit将最后一个空格添加到 列中的 MultiIndex,因此最后按 DataFrame.stack 进行整形:

df = df.set_index(['Items','Description'])
df.columns = df.columns.str.rsplit(n=1, expand=True)
df = df.rename_axis(('Store number',None), axis=1).stack(0).reset_index()
print (df)
    Items      Description Store number  Qty  Value
0  item 1   Some item name      Store 1    5    120
1  item 1   Some item name      Store 2    7    240
2  item 2  Some other item      Store 1    9   1234
3  item 2  Some other item      Store 2   12     98

关于python - 部分取消透视 pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69974521/

相关文章:

python - 匹配所有内容的 python 正则表达式是什么?

python - 直接链接到 Wagtail modeladmin View

python - Pandas read_csv 处理给定数字数据类型的带引号字符串

python - Pandas 多次从 DataFrame 添加值

r - 在数据框中的分隔符处拆分列

r - 基于行号矩阵对数据帧进行子集化,并将结果保存在一个列表中

python - subprocess.check_output 参数中的变量? [Python]

python - 创建一个新的 DataFrame,将列字典中的每个键添加为标题

python - 仅使用现有日期列中的日期时间对新 pandas 列进行矢量化计算

python - OpenERP : Saving field value (amount) into an account