0

I have a test.csv file containing the following data:

id   code
1000 60
1001 54
1002 60
1003 28

I read in .csv file into python. the columns are all 'int64'. I set 'id' as index, and want to convert the 'code' to string. I used the following code:

test = pd.read_csv("test.csv")
test = test.set_index('id')
test['code'] = test.to_string(columns = ['code'])

This is what I got in the new dataframe:

id   code
1000    code
     id    1000    60
1001    code
     id    1000    60
1002    code
     id    1000    60
1003    code
     id    1000    60

What's wrong with my code?

Thank you so much!

Hsin Lee
  • 15
  • 5
  • 4
    You are calling `.to_string` on the entire data frame, however you would like to only update the `code` column. You can do so like `test['code'] = test.code.astype(str)` – johnchase Oct 07 '19 at 17:09
  • `df['code'] = df['code'].astype(str);` `assert isinstance(df['code'][0], str)` – Brian Oct 07 '19 at 17:10
  • 1
    Possible duplicate of [Convert Columns to String in Pandas](https://stackoverflow.com/questions/22005911/convert-columns-to-string-in-pandas) – Jose R. Zapata Oct 07 '19 at 17:15
  • why don't you pass `dtype={'code':str}` to `read_csv`? – Sam Mason Oct 07 '19 at 17:15

0 Answers0