【问题标题】:pandas replace first few 0s with np.nanpandas 用 np.nan 替换前几个 0
【发布时间】:2017-11-01 16:17:50
【问题描述】:

我正在尝试用 np.nan 替换每列的 DataFrame 的第一个连续 0。比如我要转换:

pd_tmp_start = pd.DataFrame([[0,0],[0,0.3],[1.2,0.4],[0,0]])
print pd_tmp_start

     0    1
0  0.0  0.0
1  0.0  0.3
2  1.2  0.4
3  0.0  0.0

pd_tmp_target = pd.DataFrame([[np.nan,np.nan],[np.nan,0.3],[1.2,0.4],[0,0]])
print pd_tmp_target

     0    1
0  NaN  NaN
1  NaN  0.3
2  1.2  0.4
3  0.0  0.0

所以,我要做的是

pd_tmp_start[pd_tmp_start.cumsum()==0] = np.nan

虽然它有效。但是,我收到了警告

/home/myname/anaconda2/lib/python2.7/site-packages/ipykernel/ma​​in.py:1: SettingWithCopyWarning:试图在一个副本上设置一个值 从 DataFrame 切片。尝试使用 .loc[row_indexer,col_indexer] = 取而代之的价值

知道这样做的正确方法是什么吗?谢谢。

编辑:由于某种原因,前面的代码没有输出警告,但是当我处理复杂的 Dataframe 并执行 pd_tmp_start[pd_tmp_start().cumsum()==0] = np.nan

弹出警告....

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    让我们使用cumprodmask

    pd_tmp_start.mask(pd_tmp_start.eq(0).cumprod().astype(bool))
    

    输出:

        0    1
    0  NaN  NaN
    1  NaN  0.3
    2  1.2  0.4
    3  0.0  0.0
    

    以下评论更新:

    pd_tmp_start.mask(pd_tmp_start.eq(0).cumprod().astype(bool),-9876)
    

    输出:

            0       1
    0 -9876.0 -9876.0
    1 -9876.0     0.3
    2     1.2     0.4
    3     0.0     0.0
    

    【讨论】:

    • 这很棒。更重要的问题实际上是,如果我不想将其设置为 np.nan。我想将其设置为例如 -9876 ...我应该如何设置它?谢谢。
    【解决方案2】:

    你可以使用DataFrame.mask()方法:

    In [67]: pd_tmp_start = pd_tmp_start.mask(pd_tmp_start.cumsum()==0)
    
    In [68]: pd_tmp_start
    Out[68]:
         0    1
    0  NaN  NaN
    1  NaN  0.3
    2  1.2  0.4
    3  0.0  0.0
    

    【讨论】:

    • 这很棒。更重要的问题实际上是,如果我不想将其设置为 np.nan。我想将其设置为例如 -9876 ...我应该如何设置它?谢谢。
    【解决方案3】:

    pd_tmp_start 之后不需要()

    pd_tmp_start[(pd_tmp_start.cumsum()==0)]=np.nan
    pd_tmp_start
    Out[604]: 
         0    1
    0  NaN  NaN
    1  NaN  0.3
    2  1.2  0.4
    3  0.0  0.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多