0
votes

This is how I currently do it:

# Turn all table elements to strings
df = df.astype(str)
df.columns = df.columns.map(str)
df.index = df.index.map(str)

Is there a one liner that will turn df data, columns and indeces to strings?

Update

Out of curiosity I timed the various answers.

My method: 909 µs ± 37.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

@Wen's method: 749 µs ± 41.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

@COLDSPEED's method: 732 ns ± 44.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Hence the accepted answer.

2
Wrap that in a function? df_string = df_to_all_strings(df)gbtimmon
There is no need to 1-linise operations on separate objects. In this case, columns and index are separate arrays and should be converted explicitly.jpp
I don't see why this is being downvoted? I am simply looking for a more convenient way to convert all table elements to strings in a single sweep. If there is no such solution, then yes I will wrap it in a function as I have already done.Ludo
@Ludo I don't know. I don't particularly think it is a bad question, just that people who aren't aware a one liner is possible don't think the question is very good. I don't really blame you.cs95

2 Answers

4
votes

This isn't a bad question at all. Well, there's the obvious astype solution by @Wen. There are a couple of innovative solutions as well.
Let's try something a bit more interesting with operator.methodcaller.

from operator import methodcaller
df, df.columns, df.index = map(
    methodcaller('astype', str), (df, df.columns, df.index)
)
4
votes

Since you mentioned a one liner, you can recreate your df.

new_df = pd.DataFrame(
   data=df.values.astype(str),
   columns=df.columns.astype(str),
   index=df.index.astype(str)
)