我正在旋转一个幻灯片,然后对其进行过滤.然后我需要将其编写为Excel.但当我写出来时,

  1. 它在标题行和数据行之间插入一个空白行
  2. 我希望标题行名称位于一行而不是两行中.因此,在下面的Excel输出示例中,我希望列名为"Code"、"Invoice"、Unit Price"、"2022-12"、2023-12"、2024-01".我不需要顶部有"金额"的行.

可执行代码如下:

import pandas as pd
import numpy as np

df = pd.DataFrame({
        'JDate':["2022-01-31","2022-12-05","2023-11-10","2023-12-03","2024-01-16","2024-01-06"],
        # 'Month':[1,12,11,12,1,1],
        'Code':[None,'John Johnson',np.nan,'John Smith','Mary Williams','ted bundy'],
        'Unit Price':[np.nan,200,None,56,75,65],
        'Quantity':[1500, 140000, 1400000, 455, 648, 759],
        'Amount':[100, 10000, 100000, 5, 48, 59],
        'Invoice':['soccer','basketball','baseball','football','baseball','ice hockey'],
        'energy':[100.,100,100,54,98,3],
        'Category':['alpha','bravo','kappa','alpha','bravo','bravo']
})

df["JDate"] = pd.to_datetime(df["JDate"])

df["JYearMonth"] =  df['JDate'].dt.to_period('M')


index_to_use = ['Category','Code','Invoice','Unit Price']
values_to_use = ['Amount']
# columns_to_use = ['Year','Month']
columns_to_use = ['JYearMonth']


df2 = df.pivot_table(index=index_to_use,
                            values=values_to_use,
                            columns=columns_to_use)

# df3 = df2[df2['Category']=='alpha']

# since this is an index you just filter for it
# df3 = df2.loc[['alpha']]
df3 = df2.xs('alpha',level='Category')
df3 = df3.reset_index() #this prevents merging of rows


writer= pd.ExcelWriter(
        "t2test6.xlsx",
        engine='xlsxwriter'
    )


# df.to_excel(writer,sheet_name="t2",index=True)
# df2.to_excel(writer,sheet_name="t2test",index=True)
df3.to_excel(writer,sheet_name="t2filter",index=True)

writer.close()

推荐答案

xs之前切片"Amount":

df3 = (df2['Amount'].xs('alpha',level='Category')
       .reset_index().rename_axis(columns=None)
      )

输出:

         Code   Invoice  Unit Price  2022-12  2023-12  2024-01
0  John Smith  football        56.0      NaN      5.0      NaN

Python相关问答推荐

为什么自定义pytree aux_data对于jnp.数组来说在.jit()之后跟踪,而对于np.数组来说则不是?

如何从. text中进行pip安装跳过无法访问的库

合并其中一个具有重叠范围的两个框架的最佳方法是什么?

如何判断. text文件中的某个字符,然后读取该行

如何在Pygame中绘制右对齐的文本?

合并同名列,但一列为空,另一列包含值

KNN分类器中的GridSearchCV

替换字符串中的点/逗号,以便可以将其转换为浮动

在Arrow上迭代的快速方法.Julia中包含3000万行和25列的表

Locust请求中的Python和参数

即使在可见的情况下也不相互作用

Python上的Instagram API:缺少client_id参数"

为什么带有dropna=False的groupby会阻止后续的MultiIndex.dropna()工作?

使用@ guardlasses. guardlass和注释的Python继承

如何使用scipy的curve_fit与约束,其中拟合的曲线总是在观测值之下?

Python导入某些库时非法指令(核心转储)(beautifulsoup4."" yfinance)

启动带有参数的Python NTFS会导致文件路径混乱

在Python中使用if else或使用regex将二进制数据如111转换为001""

如何使regex代码只适用于空的目标单元格

在输入行运行时停止代码