Categories
Python Answers

How to convert the string 2.90K to 2900 or 5.2M to 5200000 in a Python Pandas dataframe?

Spread the love

Sometimes, we want to convert the string 2.90K to 2900 or 5.2M to 5200000 in a Python Pandas dataframe.

In this article, we’ll look at how to convert the string 2.90K to 2900 or 5.2M to 5200000 in a Python Pandas dataframe.

How to convert the string 2.90K to 2900 or 5.2M to 5200000 in a Python Pandas dataframe?

To convert the string 2.90K to 2900 or 5.2M to 5200000 in a Python Pandas dataframe, we call replace with a dict to map the patterns to new substrings and the regex argument set to True.

For instance, we write

df["Val"].replace({"K": "*1e3", "M": "*1e6"}, regex=True)

to replace the values in the Val column.

We replace the substrings in the keys with the substrings in the values by calling replace with the dict and regex set to True.

Conclusion

To convert the string 2.90K to 2900 or 5.2M to 5200000 in a Python Pandas dataframe, we call replace with a dict to map the patterns to new substrings and the regex argument set to True.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *