【问题标题】:Error: No axis named 1 for object type <class 'pandas.core.series.Series'> in python forloop on DataFrame错误:在 DataFrame 上的 python forloop 中,对象类型 <class 'pandas.core.series.Series'> 没有名为 1 的轴
【发布时间】:2020-10-03 04:21:38
【问题描述】:

我有一个数据框 x:

     T
0   1.0
1   2.0
2   NaN
3   4.0
4   5.0
5   6.0
6   7.0

如果值不是 NaN,我想将 2 乘以 cummax

编写的代码:

for i in range(len(x)):
    print(i)
    if math.isnan(x["T"].iloc[i]):
        continue
    else:
        x["T"].iloc[i] = x["T"].iloc[:i+1].cummax() * 2

但我得到了错误:

No axis named 1 for object type <class 'pandas.core.series.Series'>

期望的输出:

     T
0   2.0
1   4.0
2   NaN
3   16.0
4   32.0
5   64.0
6   128.0

【问题讨论】:

    标签: python numpy loops dataframe


    【解决方案1】:

    cummax 返回一个系列,但您只需要该系列的最后一个值:

    x["T"].iloc[i] = x["T"].iloc[:i+1].cummax().iloc[-1] * 2
    

    或者简单地不那么复杂:

    x["T"].iloc[i] = x["T"].iloc[:i+1].max() * 2
    

    【讨论】:

      猜你喜欢
      • 2017-09-02
      • 2020-06-16
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多