Home > Blockchain >  Divide column data by number if row of next column contains certain context
Divide column data by number if row of next column contains certain context

Time:08-03

Say I have a table like this

How do I let column c with x divided by 20, with y divided by 30, and with z divided by 40. I tried np.where function but I failed

CodePudding user response:

df['c'][df['a'] == 'x'] = df['c'][df['a'] == 'x']/20
df['c'][df['a'] == 'y'] = df['c'][df['a'] == 'y']/30
df['c'][df['a'] == 'z'] = df['c'][df['a'] == 'z']/40

CodePudding user response:

You can use df.apply, which will apply a given function over each row in a pandas.DataFrame. df.apply returns a new pandas.DataFrame object with the new data.

def divide(row):
    if row["a"] == "x":
        row["c"] /= 20

    elif row["a"] == "y":
        row["c"] /= 30

    elif row["a"] == "z":
        row["c"] /= 40

    return row

new_df = df.apply(divide, axis=1)
  • Related