SoFunction
Updated on 2024-11-15

Convert pandas from int to str.

I encountered a small problem today when analyzing data, and that's when I realized my basic knowledge is really not solid, so here's a record of the solution

Question:

What I get after processing the data is a list, which is put into a lot of tuples, this time I need to filter the data from the tuples to save as a csv file, but my data are all of type int, so I simply use a loop ('{},{}\n'.format(str(item[0][0]),str(item[0][1])))). Through str to convert and save as str type, but when I open the file again, I found that it is actually still int, before saving are str, really strange.

What to do at this point, in the write did not solve, so I will save it, and then open it with pandas, thinking of solving it in pandas, pandas in how to solve it? Tried for a long time, finally came up with the apply function: apply to each row or column.

I tried it, and it worked, but apply was still a bit of a pain in the ass, and needed to be modified column by column, and that's when I came up with the applymap function: apply to the whole file. Perfect!

A simple example:

import pandas as pd
import numpy as np
data = ({'m':[1,2,3,4,5],'n':[6,7,8,9,0]})
print(())
 
# data['m'] = data['m'].apply(str)
# data['n'] = data['n'].apply(str)
 
data = (str)
print(())

Here are the changes in data types before and after the modification:

Data columns (total 2 columns):
m 5 non-null int64    #int64
n 5 non-null int64
dtypes: int64(2)
 
Data columns (total 2 columns):
m 5 non-null object    #object
n 5 non-null object
dtypes: object(2)

Opened it up again to check and it was still fine, so that sort of solved the problem.

But I am very very puzzled why it doesn't change when I save the data after converting it with str. Anyone who knows about it can enlighten me, I'll still look into it again when I have time.

Above this pandas convert int type to str type method is all I share with you, I hope to give you a reference, and I hope you support me more.