gpt4 book ai didi

python - 如何根据数据框 Pandas 中列的特定条件添加一列

转载 作者:太空宇宙 更新时间:2023-11-04 11:10:47 25 4
gpt4 key购买 nike

我试过这个它创建了一个水平的列但是它未能达到结果

    df['Level'] = np.where((df['DIV0'] != '00') & (df['DIV1'] != '00') & (df['DIV2'] != '00') & (df['DIV3'] != '00'), 'NP', 'Full')
df['Level'] = np.where((df['DIV0'] != '00') & (df['DIV1'] != '00') & (df['DIV2'] != '00') & (df['DIV3'] == '00'), 'NP', 'Hu')
df['Level'] = np.where((df['DIV0'] != '00') & (df['DIV1'] != '00') & (df['DIV2'] == '00') & (df['DIV2'] == '00'), 'NP', 'Lim')
df['Level'] = np.where((df['DIV0'] != '00') & (df['DIV1'] == '00') & (df['DIV2'] == '00') & (df['DIV2'] == '00'), 'NP', 'SEG')

是否有任何方法可以创建 python 函数并使用 apply() 将该函数应用于数据框

最佳答案

您可以在不应用的情况下以不同的方式执行此操作。

dd = {1:'SEG', 2:'Lim', 3:'Hu', 4:'Full'} #Create a dictionary mapping number of Trues to level label.
df['Level'] = (df.iloc[:, 1:] != '00').sum(axis=1).map(dd)

输出:

      Final  DIV0  DIV1  DIV2  DIV3 Level
0 78797071 78 79 70 71 Full
1 23000000 23 00 00 00 SEG
2 23450000 23 45 00 00 Lim
3 45678900 45 67 89 00 Hu

解释。

使用 iloc、整数位置和切片符号,我们将位置 1 中的所有行和列返回到最后。然后我们创建一个 bool 矩阵来找出值不等于'00'的位置。现在,让我们对每一行的 True 数求和,并使用 map 使用字典将该值映射到正确的标签。

关于python - 如何根据数据框 Pandas 中列的特定条件添加一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58271141/

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