代码之家  ›  专栏  ›  技术社区  ›  Santhosh

pandas:df.loc[-1,col]有时工作,有时用NAN添加额外的行

  •  0
  • Santhosh  · 技术社区  · 3 年前

    我有一个熊猫数据框。我正在尝试修改 name

    df.loc[-1,'name'] = "something"
    

    这很管用

    df 并调用它 df_query

    数据框查询

        id  name
    21  965 kris
    

    我检查索引 -1

    df_query.loc['name'].iloc[-1]
    

    显示“克里斯”

    现在开始 数据框查询

    df_query.loc[-1,'name'] = "something"
    

    它添加了一个额外的行而不是替换 kris something

        id  name
    21  965.0 kris
    -1  NaN "something"
    

    也可以将id转换为 float int

    为什么有时有效有时无效

    后来经过搜索,我在 https://stackoverflow.com/a/49510469

    我不明白上面给出的理由

    df_query.loc[df_query.loc.index[-1],'name'] = "something"
    

    现在它起作用了。

    有人能解释一下发生了什么事吗

    2 回复  |  直到 3 年前
        1
  •  1
  •   jezrael    3 年前

    您可以选择的最后一个值 name 不同的方式-如果使用 DataFrame.loc 使用 df.index 对于索引的最后一个值,如果索引值是唯一的:

    df.loc[df.index[-1],'name'] = "something"
    

    或者如果使用 DataFrame.iloc 获取列的位置 名称 Index.get_loc :

    df.iloc[-1,df.columns.get_loc('name')] = "something"
    

    如果使用:

    df.loc[-1,'name'] = "something"
    

    index=-1 如果存在,则使用索引创建新行 -1 . 问题是如果最后一个索引没有 -1 ,但例如第一个索引,它不是替换最后一行,而是替换第一行。

    所以可能的用途是:

    #tested last value of index
    if df.index[-1] == -1:
        #last value is set
        df.loc[-1,'name'] = "something"
    
    #tested all values if index
    elif (df.index == -1).any():
        #some value with -1 is set
        df.loc[-1,'name'] = "something"
    else:
        #new row with -1 is created
        df.loc[-1,'name'] = "something"
    
        2
  •  1
  •   Mayank Porwal    3 年前

    df.tail name 带的列 something :

    df_query.tail(1)['name'] = 'something'
    

    In [629]: df = pd.read_clipboard()
    
    In [630]: df
    Out[630]: 
         id  name
    21  965  kris
    
    In [631]: df.tail(1)['name'] = 'something'
    
    In [632]: df
    Out[632]: 
         id       name
    21  965  something