简体   繁体   中英

Map Value to Specific Row and Column - Python Pandas

I have a data set where i want to match the index row and change the value of a column within that row.

I have looked at map and loc and have been able to locate the data use df.loc but it filters that data down, all i want to do is change the value in a column on that row when that row is found.

What is the best approach - my original post can be found here:

Original post

It's simple to do in excel but struggling with Pandas.

Edit:

I have this so far which seems to work but it includes a lot of numbers after the total calculation along with dtype: int64

import pandas as pd

df = pd.read_csv(r'C:\Users\david\Documents\test.csv')

multiply = {2.1: df['Rate'] * df['Quantity']}

df['Total'] = df['Code'].map(multiply)

df.head()

how do i get around this?

The pandas method mask is likely a good option here. Mask takes two main arguments: a condition and something with which to replace values that meet that condition.

If you're trying to replace values with a formula that draws on values from multiple dataframe columns, you'll also want to pass in an additional axis argument.

The condition : this would be something like, for instance:

df['Code'] == 2.1

The replacement value : this can be a single value, a series/dataframe, or (most valuable for your purposes) a function/callable. For example:

df['Rate'] * df['Quantity']

The axis : Because you're passing a function/callable as the replacement argument, you need to tell mask() how to find those values. It might look something like this:

axis=0

So all together, the code would read like this:

df['Total'] = df['Code'].mask(
    df['Code'] == 2.1,
    df['Rate'] * df['Quantity'],
    axis=0
)

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