Search code examples
pythonpandashide

Pandas style.hide() is trying to escape the quotes in variable provided


I am making a basic mistake here. I need to programmatically pre-create the string of all columns to be hidden [This is due to the behaviour of pandas style.hide(), specifically the following from the specs: "...The specified data rows/columns are hidden, but the axis-Index itself, and names, remain unchanged". It does not let me hide 1 column at a time]. Below is a simplified working example but in reality I have a multi-index column in which I need to hide certain child columns across multiple parent levels. The issue is that hide() does not have a 'escape=False' parameter so it does not escape the quotes in the string I provide, 'str_hide'. I am sure this is a 1-minute fix using some string operation...hence the 'basic mistake' part of my question. Could you please advise how to make the second part work? Thanks.

#Init
np.random.seed(0)
df = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D'])

#This works
# sdf = df.style.hide(['A', 'B'], axis='columns')

#This does not work
str_hide = "\'A\', \'B\'"
print(str_hide)  #Looks the same as above but is interpreted differently below
sdf = df.style.hide([str_hide], axis='columns')

Solution

  • Your column names are not 'A' and 'B', they are A and B. So you can simplify:

    str_hide = "A,B"
    sdf = df.style.hide(str_hide.split(','), axis='columns')