熊猫从底部得到第一个负数

问题描述 投票:0回答:1

我有以下 df。我想在其中看到最后一个结果数字之后的第一个负数。 & 在“最后一个”列的第一个负数中,“这应该出现,或者更确切地说,任何突出显示该行的内容。“这应该出现在最后一个结果数字之后的第一个负数上(结果数字可以是正数或负数&“这应该只出现针对负大米数而不是正大米数)。

import pandas as pd
import numpy as np
df1=pd.DataFrame({
        "rice": [49235.6,-49234.5,-49230.05,-49190.2,49193.1,-49140.95,-49125.3],
        "outcome": [-68.8499999999985,np.nan,np.nan,np.nan,-41.4000000000014,np.nan,np.nan,],
        "first negative from last ": [np.nan,np.nan,np.nan,np.nan,np.nan,"this",np.nan],
       })

我正在尝试使用

df.shit()

但不知道如何提出条件。

为了更好地理解以下 2 df 准确显示了“this”将出现在哪一行。

df2=pd.DataFrame({
        "rice": [49235.6,-49234.5,-49230.05,-49190.2,49193.1,49140.95,-49125.3],
        "outcome": [-68.8499999999985,np.nan,np.nan,np.nan,56,np.nan,np.nan,],
        "first negative from last ": [np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,"this"],
       })




df3=pd.DataFrame({
        "rice": [49235.6,49234.5,-49230.05,-49190.2,-49193.1,-49140.95,-49125.3],
        "outcome": [6.8499999999985,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,],
        "first negative from last ": [np.nan,np.nan,"this",np.nan,np.nan,np.nan,np.nan],
       })
pandas loops
1个回答
0
投票

代码

last_value_idx = df1['outcome'].notna().cumsum().idxmax()
target_idx = ((df1.index > last_value_idx) & (df1['rice'] < 0)).idxmax()
df1.loc[target_idx, 'first negative from last'] = 'this'

df1:

       rice  outcome first negative from last
0  49235.60   -68.85                      NaN
1 -49234.50      NaN                      NaN
2 -49230.05      NaN                      NaN
3 -49190.20      NaN                      NaN
4  49193.10   -41.40                      NaN
5 -49140.95      NaN                     this
6 -49125.30      NaN                      NaN
© www.soinside.com 2019 - 2024. All rights reserved.