python - 基于多索引列数据框中的列范围进行切片
问题描述
我正在通过执行以下操作创建我的数据框:
months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
monthyAmounts = [ "actual", "budgeted", "difference" ]
income = []
names = []
for x in range( incomeIndex + 1, expensesIndex ):
amounts = [ randint( -1000, 15000 ) for x in range( 0, len( months ) * len( monthyAmounts ) ) ]
income.append( amounts )
names.append( f"name_{x}" )
index = pd.Index( names, name = 'category' )
columns = pd.MultiIndex.from_product( [ months, monthyAmounts ], names = [ 'month', 'type' ] )
incomeDF = pd.DataFrame( income, index = index, columns = columns )
数据框看起来像:(删除月份 3 月 - 12 月)
Jan Feb ...
actual budgeted difference actual budgeted difference
name_13 14593 -260 10165 9767 629 10054
name_14 6178 1398 13620 1821 10986 -663
name_15 2432 3279 7545 8196 1052 7386
name_16 9964 13098 10342 5564 4631 7422
我想要的是每一行,将一月到五月的差异列切片。我可以通过执行以下操作来分割所有月份的差异列:
incomeDifferenceDF = incomeDF.loc[ :, idx[ :, 'difference' ] ]
这给了我一个看起来像这样的数据框:(删除了 3 月 - 12 月)
Jan Feb ....
difference difference
name_13 10165 10054
name_14 13620 -663
name_15 7545 7386
name_16 10342 7422
我尝试过的是:
incomeDifferenceDF = incomeDF.loc[ :, idx[ 'Jan' : 'May', 'difference' ] ]
但这给了我错误:
UnsortedIndexError: 'MultiIndex slicing requires the index to be lexsorted: slicing on levels [0], lexsort depth 0'
所以,这似乎很接近,但我不确定如何解决这个问题。
我也试过:
incomeDifferenceDF = incomeDF.loc[ :, idx[ ['Jan':'May'], 'difference' ] ]
但这只会产生错误:
SyntaxError: invalid syntax
( Points at ['Jan':'May'] )
做这个的最好方式是什么?
解决方案
如果需要 select by MultiIndex
,需要布尔掩码:
index = pd.Index( [1,2,3,4], name = 'category' )
budgetMonths = pd.date_range( "January, 2018", periods = 12, freq = 'BM' )
months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
monthyAmounts = [ "actual", "budgeted", "difference" ]
columns = pd.MultiIndex.from_product( [ months, monthyAmounts ], names = [ 'month', 'type' ])
incomeDF = pd.DataFrame( 10, index = index, columns = columns )
#trick for get values between
idx = pd.Series(0,index=months).loc['Jan' : 'May'].index
print (idx)
Index(['Jan', 'Feb', 'Mar', 'Apr', 'May'], dtype='object')
mask1 = incomeDF.columns.get_level_values(0).isin(idx)
mask2 = incomeDF.columns.get_level_values(1) == 'difference'
incomeDifferenceDF = incomeDF.loc[:, mask1 & mask2]
print (incomeDifferenceDF)
month Jan Feb Mar Apr May
type difference difference difference difference difference
category
1 10 10 10 10 10
2 10 10 10 10 10
3 10 10 10 10 10
4 10 10 10 10 10
推荐阅读
- node.js - 通过nodejs中的条带节点取消订阅
- kframework - 是否可以在 krun 输出的配置上调用 krun?
- spring-boot - 具有美元语法的 yaml 键值对
- python - Python检查嵌套列表中的所有项目是否相同
- ios - 向下滑动关闭时 ASWebAuthenticationSessionError.canceledLogin 不会触发
- java - 如何让 JMockit 将特定实例注入 JMockit @Tested 类?
- amazon-web-services - RI 实例的 aws 计费
- windows - 在 Windows 中构建 Rakudo 时的警告
- pycharm - 当我可以写入 Programiz 的 Online Python Compiler (Interpreter) 的 shell 时,我无法写入 PyCharm 的 shell
- vba - 如果是字符串,则将计数值粘贴到偏移列中,并加一个计数以获取下一个值