如果在datraframe python上使用multiples条件,则创建函数

2024-06-26 01:57:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有四列的数据框。你知道吗

Dataframe

我应该正常的:conso_HC=index_fin_HC-index_debut_HC。但正如你所看到的,事实并非如此,减法实际上等于。问题是,如果我们想找到consohc,有时需要在index_fin_HCindex_debut_HC中添加100000。你知道吗

 x=fichier['index_fin_HC']-fichier['index_debut_HC']
y=fichier['conso_HC']
def conditions(x,y):
    if x+100000==y:
        return x
    elif x==y+100000:
        return y
fichier['test']=fichirt

Tags: 数据hctestindexreturnifdefconditions
1条回答
网友
1楼 · 发布于 2024-06-26 01:57:45

很容易建立一个新的系列测试条件:

>>> (df.soustraction + 100000 == df.conso) | (df.soustraction - 100000 == df.conso)
0    False
1    False
2    False
3    False
4     True
5     True
6    False
dtype: bool

然后您可以:

  1. 将其作为新列添加到数据帧:

    df['condition'] = (df.soustraction + 100000 == df.conso) | (df.soustraction - 100000 == df.conso)
    
  2. 在数据帧中选择与条件匹配的行

    >>> df[(df.soustraction + 100000 == df.conso) | (df.soustraction - 100000 == df.conso)]
         debut     fin    conso  soustraction
    4  99193.0   526.0   1333.0      -98667.0
    5  91833.0  6407.0  14574.0      -85426.0
    
  3. 在数据框中选择与条件不匹配的行

    >>> df[~ ((df.soustraction + 100000 == df.conso) | (df.soustraction - 100000 == df.conso))]
         debut     fin   conso  soustraction
    0  34390.0   414.0   452.0      -33976.0
    1  18117.0    85.0   216.0      -18032.0
    2  37588.0   234.0  8468.0      -37354.0
    3  49060.0    53.0  1399.0      -49007.0
    6  38398.0  1594.0  1994.0      -36804.0
    

相关问题 更多 >