Reputation: 793
I do have a Pivottable and would like to filter the index by values contained in the index. I know how to do this for the the values greater 110 in the column "Value"
pd_pvt = pivot_table[(pivot_table['Value'] > 110)]
How would you select data (bonds only) based on their name in the index?
pd_pvt = pivot_table[(index_name['Value'] == "Bonds")]
The code above won't work, as the index can't be treated as a column
Upvotes: 1
Views: 3027
Reputation: 862501
You can try Index.get_level_values
if index name is Value
:
pd_pvt = pivot_table[(pivot_table.index.get_level_values('Value') == "Bonds")]
Sample:
pivot_table = pd.DataFrame({'Value':[200,20,34]}, index=['James','Bonds','Aa'])
pivot_table.index.name = 'Value'
print (pivot_table)
Value
Value
James 200
Bonds 20
Aa 34
pd_pvt = pivot_table[(pivot_table.index.get_level_values('Value') == "Bonds")]
print (pd_pvt)
Value
Value
Bonds 20
You can use position of levels also:
pd_pvt = pivot_table[(pivot_table.index.get_level_values(0) == "Bonds")]
print (pd_pvt)
Value
Value
Bonds 20
Or simple index
:
pd_pvt = pivot_table[(pivot_table.index == "Bonds")]
print (pd_pvt)
Value
Value
Bonds 20
Upvotes: 2