Python - turn all elements in a dataframe into strings

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

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

But that failed.

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

Then, df = [str(i) for i in df.values] to change the entire Dataframe into one big list, but it distorted the data too much to fit the purpose of my script, which should export the Dataframe to my Oracle table,

Is there a way to convert all elements that are in my Dataframe that are not rows in rows?

+10
source share
3 answers

You can use the applymap method:

 df = df.applymap(str) 
+14
source

You can use this:

 df = df.astype(str) 

Out of curiosity, I decided to see if there is a difference in efficiency between the decision made and mine.

The following are the results:

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 

df.astype run much faster :)

+19
source

This worked for me:

 dt.applymap(lambda x: x[0] if type(x) is list else None) 
0
source

Source: https://habr.com/ru/post/1015593/


All Articles