pandas lambda函数的代码应该是什么?[duplicate]

jm81lzqq  于 2022-12-09  发布在  其他
关注(0)|答案(2)|浏览(134)

此问题在此处已有答案

Pandas conditional creation of a series/dataframe column(12个答案)
昨天关门了。

这是 Dataframe 的python代码

from pandas import DataFrame
import pandas as pd
names = {'First_name': ['Hanah', 'Ria', 'Jay', 'Bholu', 'Sachin'],
'Status':['Hanah', 'Ria', 'Jay', 'Bholu', 'Sachin'],
"charge":[10,11,12,13,14]}
df = pd.DataFrame(names)

这是用于生成输出的lambda函数

df['Status'] = df['First_name'].apply(lambda x: [df["charge"]] if x == 'Ria' else 'Not Found')
print(df)

生成的输出如下:

df['Status'] = df['First_name'].apply(lambda x: [df["charge"]] if x == 'Ria' else 'Not Found')
print(df)

输出为

First_name                  Status  charge
0      Hanah               Not Found      10
1        Ria  [[10, 11, 12, 13, 14]]      11
2        Jay               Not Found      12
3      Bholu               Not Found      13
4     Sachin               Not Found      14

但我想生成输出

First_name                  Status  charge
0      Hanah               Not Found      10
1        Ria                      11      11
2        Jay               Not Found      12
3      Bholu               Not Found      13
4     Sachin               Not Found      14

第二行是Ria,因此我必须获取第二行中的charge(列)的结果,并将其置于status(列)中

b09cbbtk

b09cbbtk1#

如果要使用apply和lambda函数,请将lambda函数应用于所有带有axis=1 Dataframe

df['Status'] = df.apply(lambda x: x['charge'] if x['First_name'] == 'Ria' else 'Not Found', axis=1)

df

First_name  Status  charge
0   Hanah       Not Found   10
1   Ria         11          11
2   Jay         Not Found   12
3   Bholu       Not Found   13
4   Sachin      Not Found   14

但我们可以用mask代替apply

cond1 = df['First_name'].ne('Ria')
df.assign(Status=df['charge'].mask(cond1, 'Not Found'))

实验结果:

First_name  Status  charge
0   Hanah       Not Found   10
1   Ria         11          11
2   Jay         Not Found   12
3   Bholu       Not Found   13
4   Sachin      Not Found   14
pdtvr36n

pdtvr36n2#

lambda可用于def函数的位置First_name Status charge 0 Hanah未找到10 1 Ria 11 11 2 Jay未找到12 3 Bholu未找到13 4 Sachin未找到14使用def可轻松连接此表

相关问题