Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Turn all items in a Dataframe to strings

I followed the following procedure: In Python, how do I convert all of the items in a list to floats? because each column of my Dataframe is list, but instead of floats I chose to change all the values to strings.

df = [str(i) for i in df]

But this failed.

It simply erased all the data except for the first row of column names.

Then, trying df = [str(i) for i in df.values] resulted in changing the entire Dataframe into one big list, but that messes up the data too much to be able to meet the goal of my script which is to export the Dataframe to my Oracle table.

Is there a way to convert all the items that are in my Dataframe that are NOT strings into strings?

like image 839
theprowler Avatar asked Mar 08 '17 16:03

theprowler


People also ask

How do I convert a DataFrame to a string in Python?

You can convert the column “Fee” to a string by simply using DataFrame. apply(str) , for example df["Fee"]=df["Fee"]. apply(str) .

What is Tolist () in pandas?

Pandas series can be converted to a list using tolist() or type casting method. There can be situations when you want to perform operations on a list instead of a pandas object. In such cases, you can store the DataFrame columns in a list and perform the required operations.

How do I convert a whole DataFrame to a list?

To convert Pandas DataFrame to List in Python, use the DataFrame. values(). tolist() function.


1 Answers

You can use this:

df = df.astype(str) 

out of curiosity I decided to see if there is any difference in efficiency between the accepted solution and mine.

The results are below:

example df:

df = pd.DataFrame([list(range(1000))], index=[0]) 

test df.astype:

%timeit df.astype(str)  >> 100 loops, best of 3: 2.18 ms per loop 

test df.applymap:

%timeit df.applymap(str) 1 loops, best of 3: 245 ms per loop 

It seems df.astype is quite a lot faster :)

like image 126
PdevG Avatar answered Oct 25 '22 15:10

PdevG