[英]Access last elements of inner multiindex level in pandas dataframe
在multi index
pandas數據幀中,我想訪問第一個索引的所有值的第二個索引的最后一個元素。 第二個索引中的級別數取決於第一個索引的值。 我瀏覽了pandas多索引文檔,但找不到任何可以做到這一點。
例如,對於以下數據框:
arrays = [ ['bar', 'bar', 'baz', 'foo', 'foo', 'foo', 'qux'],
['one', 'two', 'one', 'one', 'two', 'three', 'one']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(7, 3), index=index, columns=['A', 'B', 'C'])
df
A B C
first second
bar one 0.289163 -0.464633 -0.060487
two 0.224442 0.177609 2.156436
baz one -0.262329 -0.248384 0.925580
foo one 0.051350 0.452014 0.206809
two 2.757255 -0.739196 0.183735
three -0.064909 -0.963130 1.364771
qux one -1.330857 1.881588 -0.262170
我想得到:
A B C
first second
bar two 0.224442 0.177609 2.156436
baz one -0.262329 -0.248384 0.925580
foo three -0.064909 -0.963130 1.364771
qux one -1.330857 1.881588 -0.262170
我正在使用的dataframes
有超過10M
行,所以我想避免顯式循環。
print (df.groupby(level='first').tail(1))
A B C
first second
bar two 0.053054 -0.555819 0.589998
baz one -0.868676 1.293633 1.339474
foo three 0.407454 0.738872 1.811894
qux one -0.346014 -1.491270 0.446772
因為last
失去了level second
:
print (df.groupby(level='first').last())
A B C
first
bar 0.053054 -0.555819 0.589998
baz -0.868676 1.293633 1.339474
foo 0.407454 0.738872 1.811894
qux -0.346014 -1.491270 0.446772
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.