【问题标题】:IF statement Panda Dataframe: The truth value of a Series is ambiguousIF 语句 Pandas Dataframe:Series 的真值是模棱两可的
【发布时间】:2017-12-21 21:48:02
【问题描述】:

我有一个只有浮点数据的数据框。我基本上想创建一个新列,如果它满足条件,它将从另一列获取值,如果不满足,则从另一列获取值。 我所有的列都是浮点型的。

for col in list_scenarios:
    df_merged['in_scenario_'+ col] = 1.0
    print(df_merged['in_scenario_' + col])
    if df_merged[col].shift(1)== 1.0:
        df_merged['in_scenario_' + col] = df_merged['in_scenario_'+ col].shift(1)*df_merged[asset +'_r']
    else:
        df_merged['in_scenario_' + col] = df_merged['in_scenario_'+ col].shift(1)
    print(df_merged['in_scenario_' + col])

我收到以下错误:

    Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2017.3.1\helpers\pydev\pydev_run_in_console.py", line 52, in run_file
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2017.3.1\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/Main/PycharmProjects/Macrobond_API/scenario testing.py", line 268, in <module>
    if df_merged[col].shift(1)== 1.0:
  File "C:\Users\Main\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\generic.py", line 1121, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我不知道什么是模棱两可的。

谢谢

My dataframe looks like this (month year are indices)
            sp500_500  USA  MEXICO  sp500_500_r
month year                                                           
6     2017   2423.41  1.0      1.0     0.004814
7     2017   2470.30  1.0      1.0     0.019349
8     2017   2471.65  1.0      1.0     0.000546

【问题讨论】:

  • 为什么不使用嵌套的np.where

标签: python pandas dataframe ambiguous


【解决方案1】:

df_merged[col].shift(1)== 1.0你比较两种不同的类型 df_merged[col].shift(1) 返回一个数据框。如果要获取该列的第一个值,可以使用 iloc。 df_merged[col].iloc[0] == 1.0

a
   x  
0   0   
1   1   
2   2   
3   3   
4   4   

a.x.shift(1)

   x  
0   NaN   
1   1   
2   2   
3   3   
4   4  

a.x.iloc[0]

1

【讨论】:

  • 问题是我一直在寻找相对而不是绝对位置。
  • @RomM 你可以改变它。它取决于什么?
  • 基本上就是遍历每一行。取一列之前或之后的值,对另一列进行操作。我对 STATA 有点习惯,但对 python 不习惯。
【解决方案2】:

我实际上找到了解决方法。

for col in list_scenarios:
    df_merged['in_scenario_'+ col] = df_merged[asset +'_r']
    df_merged[col] = df_merged[col].shift(1)
    df_merged.loc[df_merged[col] ==0, 'in_scenario_'+ col] = 0

这给了我想要的“回报”。然后我只需要从这个以 1 作为第一个值开始的返回值构建索引。

感谢您的帮助。

【讨论】:

    猜你喜欢
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 2021-02-01
    相关资源
    最近更新 更多