0

I have a dataframe which I read from a CSV as:

df = pd.read_csv(csv_path, header = None)

By default, Pandas assigns the header (df.columns) to be [0, 1, 2, ...] of type int64
What's the best way to to convert this to type str, such that df.columns results in ['0', '1', '2',...] (i.e type str)?
Currently, the best way I can think of doing this is df.columns = list(map(str, df.columns))
Unfortunately, df.astype(str) only affects the values and not the column names

1 Answer 1

1

You can use astype(str) with column names like this:

df.columns = df.columns.astype(str)

Example:

In [2472]: l = [1,2]
In [2473]: l1 = [2,3]

In [2475]: df = pd.DataFrame([l, l1])

In [2476]: df
Out[2476]: 
   0  1
0  1  2
1  2  3

In [2480]: df.columns = df.columns.astype(str)

In [2482]: df.columns
Out[2482]: Index(['0', '1'], dtype='object')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.