0

I have a Pandas Data Frame (called df) so that one of its columns is called Revenue. I just wanted to change the elements of this column using the lambda function as follows but I have a problem accessing the indices of the elements:

df['Revenue']=df['Revenue'].apply(lambda d: Output:(a function of index of d in Revenue) Conditional statement)

I need to place the index of d inside the lambda function but do not know how to do so.

1

1 Answer 1

1

You can analyze this example. Source

# importing pandas and numpylibraries
import pandas as pd
import numpy as np
 
# creating and initializing a nested list
values_list = [[15, 2.5, 100], [20, 4.5, 50], [25, 5.2, 80],
               [45, 5.8, 48], [40, 6.3, 70], [41, 6.4, 90],
               [51, 2.3, 111]]
 
# creating a pandas dataframe
df = pd.DataFrame(values_list, columns=['Field_1', 'Field_2', 'Field_3'],
                  index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
 
 
# Apply function numpy.square() to square
# the values of 3 rows only i.e. with row
# index name 'a', 'e' and 'g' only
df = df.apply(lambda x: np.square(x) if x.name in [
              'a', 'e', 'g'] else x, axis=1)
df

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Dear Uozcan but it does not work for me and returns AttributeError: 'float' object has no attribute 'name'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.