[英]python pandas multiindex subtract rows with matching level 1 index
熊貓DataFrame:
構造函數:
iterables = [[date(2018,5,31),date(2018,6,26),date(2018,6,29),date(2018,7,1)],
['test1','test2']]
indx = pd.MultiIndex.from_product(iterables, names=['date','tests'])
col = ['tests_passing', 'tests_total']
data = np.array([[834,3476],[229,256],[1524,1738],[78,144],[1595,1738],[78,144],[1595,1738],[142,144]])
df = pd.DataFrame(data, index=indx, columns=col)
df = df.assign(tests_remaining= df['tests_total'] - df['tests_passing'])
數據框:
tests_passing tests_total tests_remaining
date tests
2018-05-31 test1 834 3476 2642
test2 229 256 27
2018-06-26 test1 1524 1738 214
test2 78 144 66
2018-06-29 test1 1595 1738 143
test2 78 144 66
2018-07-01 test1 1595 1738 143
test2 142 144 2
此數據由一些在某個日期收集的測試測量值(test1,test2等)組成。 我想在此數據框中創建一個名為“ progress”的新列,該列通常會選擇所有日期中test =唯一測試(例如,test1)的所有行,並在date0減去該行的“ tests_remaining”列值,並添加下一個date1,date2等的行的值基本上是這樣的: df.loc[(date0,test0),'progress'] = df.loc[(date0,test0),'tests_remaining']-df.loc[(date1,test0),'tests_remaining]
(但有一個例外,因為第一個日期是第一個收集的日期,所以其進度值為0)。
所需的輸出將如下所示:
tests_passing tests_total tests_remaining progress
date tests
5/31/2018 test1 834 3476 2642 0
test2 229 256 27 0
6/26/2018 test1 1524 1738 214 2428
test2 78 144 66 -39
6/29/2018 test1 1595 1738 143 71
test2 78 144 66 0
7/1/2018 test1 1595 1738 143 0
test2 142 144 2 64
到目前為止,我已經能夠使用帶有切片的loc []一次選擇一個測試並將其作為結果熊貓系列執行此計算,但是如果沒有在中明確指定測試名稱,我通常無法在所有測試中執行此操作分裂。 這對我來說不是一個合理的解決方案,因為在真實數據中有數百種測試。
All = slice(None)
df_slice = df.loc[(All,'test1'),'tests_remaining']
sub = df_slice.diff(periods=-1).shift(1).fillna(0);sub
date tests
2018-05-31 test1 0.0
2018-06-26 test1 2428.0
2018-06-29 test1 71.0
2018-07-01 test1 0.0
Name: tests_remaining, dtype: float64
有沒有更多的熊貓慣用方式來創建所需的列,如上所述?
在此先感謝您的幫助!
您可以按級別groupby
測試並進行diff
df.groupby(level='tests').tests_remaining.diff().mul(-1)
Out[662]:
date tests
2018-05-31 test1 NaN
test2 NaN
2018-06-26 test1 2428.0
test2 -39.0
2018-06-29 test1 71.0
test2 -0.0
2018-07-01 test1 -0.0
test2 64.0
Name: tests_remaining, dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.