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

Time:10-24

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.

CodePudding user response:

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)
  • Related