Home > Back-end >  calling key in dataframe returns keyerror
calling key in dataframe returns keyerror

Time:10-07

I am trying to retrieve data by using the keys that I assigned when using the concat function, however, it always returns keyerror.

for example:

lists = pd.DataFrame({ "no_1": [1,2,3,4]})
x = pd.DataFrame( {"no_2": [3,3,4,5]})
total = pd.concat([lists, x], axis=0, keys=["a", "b"])
print(total["a"])

This will return keyerror 'a'. It ought to print the data assigned under the key 'a'.

CodePudding user response:

Calling total["a"] tries to retrieve column "a" from the dataframe total, while "a" is an index (a row identifier) here.

To select such an index, you need to use total.loc["a"] instead.

CodePudding user response:

Try this:

total.loc[total.index.get_level_values(0) == 'a']

CodePudding user response:

I think what you want is to use axis=1 (columns) instead of axis=0 (index) in pd.concat:

total = pd.concat([lists, x], axis=1, keys=["a", "b"]) 
print(total["a"])

# Output:
   no_1
0     1
1     2
2     3
3     4
  • Related