How to query MultiIndex index columns values in pandas

To query the df by the MultiIndex values, for example where (A > 1.7) and (B < 666): In [536]: result_df = df.loc[(df.index.get_level_values(‘A’) > 1.7) & (df.index.get_level_values(‘B’) < 666)] In [537]: result_df Out[537]: C A B 3.3 222 43 333 59 5.5 333 56 Hence, to get for example the ‘A’ index values, if still … Read more

Pandas dataframe with multiindex column – merge levels

There is potentially a better way, more pythonic way to flatten MultiIndex columns. 1. Use map and join with string column headers: grouped.columns = grouped.columns.map(‘|’.join).str.strip(‘|’) print(grouped) Output: code colour size|sum size|average size|size size|idxmax \ 0 one black 862 53.875000 16 14 1 one white 554 46.166667 12 18 2 three black 842 49.529412 17 90 … Read more

Resampling Within a Pandas MultiIndex

pd.Grouper allows you to specify a “groupby instruction for a target object”. In particular, you can use it to group by dates even if df.index is not a DatetimeIndex: df.groupby(pd.Grouper(freq=’2D’, level=-1)) The level=-1 tells pd.Grouper to look for the dates in the last level of the MultiIndex. Moreover, you can use this in conjunction with … Read more

pandas dataframe select columns in multiindex [duplicate]

There is a get_level_values method that you can use in conjunction with boolean indexing to get the the intended result. In [13]: df = pd.DataFrame(np.random.random((4,4))) df.columns = pd.MultiIndex.from_product([[1,2],[‘A’,’B’]]) print df 1 2 A B A B 0 0.543980 0.628078 0.756941 0.698824 1 0.633005 0.089604 0.198510 0.783556 2 0.662391 0.541182 0.544060 0.059381 3 0.841242 0.634603 0.815334 … Read more

Construct pandas DataFrame from items in nested dictionary

A pandas MultiIndex consists of a list of tuples. So the most natural approach would be to reshape your input dict so that its keys are tuples corresponding to the multi-index values you require. Then you can just construct your dataframe using pd.DataFrame.from_dict, using the option orient=”index”: user_dict = {12: {‘Category 1’: {‘att_1’: 1, ‘att_2’: … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)