1

I need to convert all columns of a csv file into str while reading with Pandas in python. What is the most efficient way to write this code?

df = pd.read_csv("datafile.csv", sep = "\s+", names = ["lvl12",
"etime", "press", "gph", "temp", "rh", "dpdp", "wdir", "wspd"])
df['lvl12'].astype(str)
df['etime'].astype(str)
df['press'].astype(str)
df['gph'].astype(str)
df['temp'].astype(str)
df['rh'].astype(str)
df['dpdp'].astype(str)
df['wdir'].astype(str)
df['wspd'].astype(str)
1
  • df=df.astype(str) Commented Mar 23, 2018 at 4:22

2 Answers 2

3

You can do one better; add the dtype=str argument when reading df in:

df = pd.read_csv(
    "datafile.csv", 
    sep="\s+", 
    names=["lvl12", "etime", "press", ...],
    dtype=str
)
Sign up to request clarification or add additional context in comments.

2 Comments

Yep , I am thinking of this way :-)
That's awesome! There are so many useful key-word arguments lurking in pandas.
0

You can call astype on the whole dataframe at once:

df.astype(str)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.