Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I round a PANDAS dataframe column in the same line that I edit the column?

Using Python 3.9

Using PANDAS, I’m trying to convert a column from feet to meters and then round the answer to three decimals. I currently have this:

df['col_m'] = df[col_f] * 0.3048
df['col_m'] = df['col_m'].round(3)

It gets the job done but is there a more efficient way to do this? Is it possible to do both actions in one line? I tried a couple different methods but the rounding ends up occurring too early if not separated like this. Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To perform it in one step, just chain the operations. Using mul in place of * makes it more convenient as you won’t need parentheses (in comparison to (df[col_f] * 0.3048).round(3)):

df['col_m'] = df[col_f].mul(0.3048).round(3)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading