I have a dataframe that's giving me issues when I try to merge it with another. I keep getting a keyerror on one of the columns so my guess is this column somehow is dropping off.

print(DF.head())
print(DF.columns.values)

The first part that is returned is as expected:

                                      Quantity
STORE_NMBR CLASS             TYPE             
6          EQUIPMENT         3414001        22
                             3418560        10
                             3463731         1
                             3480019       980
                             3483920         1

the second is not:

['Quantity']

I'm pretty much a newb in python so have no idea why this is happening.

1 Answers

1
HS-nebula On Best Solutions

It looks like you have a MultiIndex in your dataframe. You can fix if by setting DF=DF.reset_index()

For instance,

df = pd.DataFrame({'STORE_NMBR':[6]*5, 'CLASS':['EQUIPMENT']*5, 
               'TYPE': [3414001,3418560,3463731,3480019,3483920], 
               'Quantity':[22,10,1,980,1]})

df = df.set_index(['STORE_NMBR', 'CLASS', 'TYPE'])

                                      Quantity
STORE_NMBR CLASS             TYPE             
6          EQUIPMENT         3414001        22
                             3418560        10
                             3463731         1
                             3480019       980
                             3483920         1   

df = df.reset_index()

    STORE_NMBR    CLASS        TYPE     Quantity
0         6     EQUIPMENT   3414001     22
1         6     EQUIPMENT   3418560     10
2         6     EQUIPMENT   3463731     1
3         6     EQUIPMENT   3480019     980
4         6     EQUIPMENT   3483920     1

print(df.columns)

### Outputs
['STORE_NMBR', 'CLASS', 'TYPE', 'Quantity']