简体   繁体   中英

Update value if a condition in the adjacent cell is true

I'm using Pandas to read a CSV data file into a DataFrame. The data is basically a bunch of dimensions in one column and the next one is the unit.

IE

  Perameter  | measurement | unit
      Height |     72      |  inches
      Length |     20      |  mm

I would then like to search through the DataFrame, find all places where the unit does not match what it should (ie lbs vs kg) and then simply convert it to the units that the rest of the script uses.

I'm stumped on how to search through based on one column, read that value, divide/multiply that value by the conversion factor, then replace the value in the DataFrame.

I can't get this to work:

df = pd.read_csv('path/to/Input.csv')

data.loc[ data.Units == 'in' ] = x
data[measurement][x] = ((data[measurement][x])/25.4) # convert to mm.

Any ideas?

You can do this:

# Multiply the measurement by 25.4 where unit is inches
df.loc[df.unit == 'inches', 'measurement'] *= 25.4
# Replace `inches` with `mm` in unit column after it's been converted
df['unit'].replace('inches', 'mm', inplace=True)

>>> df
  Perameter  measurement unit
0    Height       1828.8   mm
1    Length         20.0   mm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM