IF声明Panda Dataframe:系列的真值是模棱两可的

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

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

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
python pandas dataframe ambiguous
2个回答
1
投票

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

df_merged[col].shift(1)

0
投票

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

df_merged[col].iloc[0] == 1.0

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

谢谢你的帮助。

© www.soinside.com 2019 - 2024. All rights reserved.