How can I apply a function to each row in a pandas dataframe?

Viewed 1278

I am pretty new to coding so this may be simple, but none of the answers I've found so far have provided information in a way I can understand.

I'd like to take a column of data and apply a function (a x e^bx) where a > 0 and b < 0. The (x) in this case would be the float value in each row of my data.

See what I have so far, but I'm not sure where to go from here....

def plot_data():

    # read the file
    data = pd.read_excel(FILENAME)

    # convert to pandas dataframe
    df = pd.DataFrame(data, columns=['FP Signal'])

    # add a blank column to store the normalized data
    headers = ['FP Signal', 'Normalized']
    df = df.reindex(columns=headers)
    df.plot(subplots=True, layout=(1, 2))
    df['Normalized'] = df.apply(normalize(['FP Signal']), axis=1)
    print(df['Normalized'])
    # show the plot
    plt.show()

# normalization formula (exponential) = a x e ^bx where a > 0, b < 0
def normalize(x):
    x = A * E ** (B * x)
    return x

I can get this image to show, but not the 'normalized' data...

Subplot image of raw data and normalized data

thanks for any help!

2 Answers

Your code is almost correct.

# normalization formula (exponential) = a x e ^bx where a > 0, b < 0
def normalize(x):
    x = A * E ** (B * x)
    return x

def plot_data():

    # read the file
    data = pd.read_excel(FILENAME)

    # convert to pandas dataframe
    df = pd.DataFrame(data, columns=['FP Signal'])

    # add a blank column to store the normalized data
    headers = ['FP Signal', 'Normalized']
    df = df.reindex(columns=headers)
    df['Normalized'] = df['FP Signal'].apply(lambda x: normalize(x))
    print(df['Normalized'])
    df.plot(subplots=True, layout=(1, 2))
    # show the plot
    plt.show()

I changed apply row to the following: df['FP Signal'].apply(lambda x: normalize(x)). It takes only the value on df['FP Signal'] because you don't need entire row. lambda x states current values assign to x, which we send to normalize.

You can also write df['FP Signal'].apply(normalize) which is more directly and more simple. Using lambda is just my personal preference, but many may disagree.

One small addition is to put df.plot(subplots=True, layout=(1, 2)) after you change dataframe. If you plot before changing dataframe, you won't see any change in the plot. df.plot actually doing the plot, plt.show just display it. That's why df.plot must be after you done processing your data.

You can use map to apply a function to a field

pandas.Series.map


s = pd.Series(['cat', 'dog', 'rabbit'])
s.map(lambda x: x.upper())
0       CAT
1       DOG
2    RABBIT
Related