Here's my data
my dataframe name is tab
user_id len
barcode
0 1 490
1 2 71
2 3 1
3 5 1
This is my code
tab = tab[tab[('len', 'barcode')]]
tab.columns
MultiIndex(levels=[['len', 'user_id'], ['barcode', '']],
labels=[[1, 0], [1, 0]])
This code on my routine notebook and works more than 10 times, but it not works anymore
I think there is problem your second level name is empty string.
So need:
a = tab[('len', '')]
print (a)
0 490
1 71
2 1
3 1
Name: (len, ), dtype: int64
If you want replace all empty strings in columns names:
tab = tab.rename(columns={'':'b'})
a = tab[('len', 'b')]
print (a)
0 490
1 71
2 1
3 1
Name: (len, b), dtype: int64
But better is remove []
for remove MultiIndex in columns:
tab = pd.pivot_table(barcode,index="user_id",values="barcode",aggfunc='size')
tab = tab.reset_index()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With