votes up 1

The following 'value_vars' are not present in the DataFrame: (list(missing))

Package:
pandas
github stars 30911
Exception Class:
KeyError

Raise code

"value_vars must be a list of tuples when columns are a MultiIndex"
            )
        else:
            value_vars = list(value_vars)
            # Check that `value_vars` are in frame
            missing = Index(com.flatten(value_vars)).difference(cols)
            if not missing.empty:
                raise KeyError(
                    "The following 'value_vars' are not present in "
                    f"the DataFrame: {list(missing)}"
                )
        if col_level is not None:
            idx = frame.columns.get_level_values(col_level).get_indexer(
                id_vars + value_vars
            )
        else:
ūüė≤ Agile task management is now easier than calling a taxi. #Tracklify

Ways to fix

votes up 2 votes down

# Melt Lat and Lon into a new dataframe

uber_jun= pd.melt(uber_jun, value_vars=['Lat', 'Lon'], var_name='Lat/Lon', value_name='Val')

# Print last eight lines of new dataframe

uber_jun.tail(5)

Jan 03, 2022 jeykbarretto answer
votes up 0 votes down

CODE TO REPRODUCE(WRONG):

from pandas.core.indexes.api import MultiIndex
import numpy as np

df = pd.DataFrame(np.zeros((2,4)))
df.columns = pd.MultiIndex.from_arrays([['a','a','b','b'],[1,2,1,2]])
pd.melt(df, value_vars=[['X']]) # Passing an unknown key to the value_vars argument

Gives:

85             if not missing.empty:
     86                 raise KeyError(
---> 87                     "The following 'value_vars' are not present in "
     88                     f"the DataFrame: {list(missing)}"
     89                 )

KeyError: "The following 'value_vars' are not present in the DataFrame: ['X']"

WORKING SOLUTION (FIXED):

from pandas.core.indexes.api import MultiIndex
import numpy as np

df = pd.DataFrame(np.zeros((2,4)))
df.columns = pd.MultiIndex.from_arrays([['a','a','b','b'],[1,2,1,2]])
pd.melt(df, value_vars=['a'])

Result:

ariable_0	variable_1	value
0	b	2	0.0
1	b	2	0.0

Jun 14, 2021 brucehardywald answer

Add a possible fix

Please authorize to post fix