Title: Wanted: function to remove whitespace from column headers that is robust to column headers not being strings
Tags: python;pandas;dataframe;strip
Question: I get my data into pandas dataframes, and normally clean up my column headers with
df.columns = df.columns.str.strip()
However I recently encountered a dataframe that had integer type column names, not strings.  When I tried and do a .str.strip() it throws an error.
How would I write some python code that strips whitespace from the column names if they are strings.
I'm new to python, so the more hand holding the better.
Thanks
Comment: You want to know how to remove whitespace from strings (which you seem to know how to do) in order to handle column names that are integers?

Here is the accepted answer: You could use a list comprehension, which is quite unusual when working with Pandas as it's usually more efficient to apply built-in Pandas functions (as you've done). But for something as simple as fixing column names, this should be fine:
df = pd.DataFrame(columns=[1, 2, 'A '])
df.columns = [col.strip() if isinstance(col, str) else col for col in df.columns]
Results:
In [75]: df.columns
Out[75]: Index([1, 2, 'A'], dtype='object')

Here is another answer: The safest option is to convert all the column names to strings (so df[0] -> df['0']) before you do this:
df.rename(columns={c: str(c).strip() for c in df.columns}, inplace=True)
This uses a dictionary comprehension to iterate over the column names df.columns and then create a mapping from the original column name c to a string version str(c). It then uses the native .strip() string method. You execute it as a one-liner by using inplace=True.
Closer to the intent of the original question is:
df.columns = [col.strip() if isinstance(col, str) else col for col in df.columns]
...but I would suggest not using this, as numeric column names can be confusing (for example, if column 5 is in position 3). With the string name, it is clear that this is not a positional value.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:11/28/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><pandas><dataframe><strip>', 'Title': 'Wanted: function to remove whitespace from column headers that is robust to column headers not being strings', 'ViewCount': 63, 'id': 53510121, 'user_AboutMe': None, 'user_AccountId': 7724574.0, 'user_DisplayName': 'Andrewfreestuff', 'user_Reputation': 161.0, 'user_Views': 20.0, 'user_id': 5849633.0}}