从多级列索引中删除列

时间:2019-08-26 10:24:36

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

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

只需要动态地在特定列(月)上删除一个子列

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

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

1 个答案:

答案 0 :(得分: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