【问题标题】:drop a column from a multi-level column index从多级列索引中删除一列
【发布时间】:2019-12-30 12:53:31
【问题描述】:

需要删除从数据透视表创建的多索引数据框的子列

只需要动态删除特定列(月)的子列

我有一个从数据透视表创建的数据框,需要动态删除特定列的子列...
如果今天的日期小于 15,我需要删除除 Sep-19 以外所有月份的子栏 Bill1(当月)
如果今天的日期大于 15,则应删除除 Oct-19(下个月)

data_frame1 = pd.pivot_table(data_frame, index=['PC', 'Geo', 'Comp'], values=['Bill1', 'Bill2'], columns=['Month'], fill_value=0)
data_frame1 = data_frame1.swaplevel(0,1, axis=1).sort_index(axis=1)
tuples = [(a.strftime('%b-%y'), b) if a!= 'All' else (a,b) for a,b in data_frame1.columns]
data_frame1.columns = pd.MultiIndex.from_tuples(tuples)

输出:

              jan-19             Feb-19        Mar-19
             Bill1 Bill2      Bill1 Bill2     Bill1 Bill2     
PC Geo Comp
A  Ind   OS   1     1.28        1    1.28      1    1.28

所需的输出:

               jan-19      Feb-19       Mar-19
               Bill2       Bill2     Bill1 Bill2     
PC Geo Comp
A  Ind   OS     1.28        1.28      1    1.28

【问题讨论】:

  • 你能过滤pd.pivot_table之前的数据框吗?老实说,这将是最简单的。
  • 首先我认为,在旋转之前进行过滤是个好主意,但我认为它不适用于这种情况,因为 Bill1 和 Bill2 可能是源数据框中的两列,因此不能过滤。
  • @jottbe...你能回答我的问题吗?...我修改了我的问题...请检查一下
  • @jezrael...兄弟有什么帮助吗?
  • 快速尝试一下。我猜你的意思是上面的粗体字,对吧?如果你只是将next_month_date=datetime(next_month_year, next_month, 1) 更改为next_month_date=datetime(next_month_year, next_month, 15),你得到你想要的输出了吗?

标签: python-3.x pandas pivot-table


【解决方案1】:

看来jezrael正在度假,所以我试试看:-)

你可以这样做:

from datetime import datetime
import calendar

# get the date of the 1st day in the next month (using the system date)
now= datetime.now()
next_month_year, next_month= calendar.nextmonth(now.year, now.month)
next_month_date=datetime(next_month_year, next_month, 1)

# get all dates in the data for which we might have to delete columns
dates_to_correct= df.loc[df['Month'] < next_month_date, 'Month'].dt.strftime('%b-%y').unique()

# filter the columns to be deleted
cols_to_delete= [col for col in data_frame1.columns if col[1] == 'Bill1' and col[0] in dates_to_correct]
data_frame1.drop(cols_to_delete, axis='columns', inplace=True)

也许看起来有点复杂,但因为我不知道您的数据中是否只有下个月或未来几个月,所以我认为比较日期可能更安全,而不仅仅是做类似的事情column_string_date != string_for_next_month.

基于此示例数据

df= pd.DataFrame({
        'PC':    ['foo', 'bar'],
        'Geo':   ['here', 'there'],
        'Comp':  ['Telekom', 'Daimler'],
        'Bill1': [17.19, 21.23],
        'Bill2': [17.18, 21.22],
        'Month': ['2019-08-01', '2019-09-01'],
    })

df['Month']= df['Month'].astype('datetime64')

我们得到:

Out[56]: 
                  Aug-19 Sep-19       
                   Bill2  Bill1  Bill2
PC  Geo   Comp                        
bar there Daimler   0.00  21.23  21.22
foo here  Telekom  17.18   0.00   0.00

【讨论】:

    猜你喜欢
    • 2014-09-27
    • 2023-04-02
    • 2018-08-03
    • 2023-04-05
    • 2019-03-19
    • 2021-12-05
    相关资源
    最近更新 更多