gpt4 book ai didi

python - 如何根据数据框中的列条件应用函数

转载 作者:行者123 更新时间:2023-12-01 06:49:06 25 4
gpt4 key购买 nike

我正在尝试在数据帧中的列上应用函数,如果其中一列(即 df['mask'] )包含 False,则它应该跳过该行。 mask列是bool类型

这是我的功能

     def dates(inp):
temp = inp
parser = CommonRegex()
inp = inp.apply(parser.dates).str.join(', ')
return np.where(inp.apply(parser.dates).str.len() == 0, temp, 'X' * random.randrange(3, 8))

这是我所申请的

      df1.assign(**df1['Dates'].apply(dates).where(df1['mask']== TRUE))

它的抛出错误

         32     temp = inp
33 parser = CommonRegex()
---> 34 inp = inp.apply(parser.dates).str.join(', ')
35 return np.where(inp.apply(parser.dates).str.len() == 0, temp, 'X' * random.randrange(3, 8))
36

AttributeError: 'Timestamp' object has no attribute 'apply'

这是我的数据框,看起来像

         Name     |  Dates   |  mask |
..............................
Tom | 21/02/2018| True
Nick | 28/07/2018| False
Juli | 11/08/2018| True
June | 01/02/2018| True
XHGM | 07/08/2018| False

我试图以这种方式获取输出,对于假​​值,它应该跳过,对于真值,它应该调用日期函数并隐藏数据值

         Name     |  Dates   |  mask |
..............................
Tom | XXXXX | True
Nick |28/07/2018 | False
Juli | XXXXX | True
June | XXXXX | True
XHGM | 07/08/2018| False

最佳答案

使用Series.pipe用于传递列来运行并使用 boolean indexing 过滤行通过面具和 DataFrame.loc用于指定列名称:

df1.loc[df1['mask'], 'Dates'] = df1.loc[df1['mask'], 'Dates'].pipe(dates)
print (df1)
Name Dates mask
0 Tom XXX True
1 Nick 28/07/2018 False
2 Juli XXX True
3 June XXX True
4 XHGM 07/08/2018 False

使用分配的解决方案也是可能的,但缺点是函数循环所有值然后进行过滤,因此如果大Dataframe<中只有几个True 应该更慢:

df1 = df1.assign(Dates = np.where(df1['mask'], df1['Dates'].pipe(dates), df1['Dates']))

关于python - 如何根据数据框中的列条件应用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59104676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com