简体   繁体   中英

How to get the index of elements inside lambda function in pandas

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.

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

在此处输入图像描述

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