【问题标题】:Replacing values in a pandas dataframe taking row number into account考虑行号替换熊猫数据框中的值
【发布时间】:2022-10-14 04:08:48
【问题描述】:

我有这个从 excel 文件中获取的数据框,如果状态为“否”,我想用包含行号的字符串(+1 和 F,因此它引用 excel 中的另一个单元格)替换值列。我没有问题替换评论列中的一些值

df.loc[df["state"] == "no", "comment"] = ""

但我不知道如何考虑行号。

输入:

         state  value  comment
0         yes     6    example1
1          no    34    example2    
2          no    25    example3
3         yes   123    example4
4          no    55    example5

输出:

         state  value  comment
0         yes     6    example1
1          no   =F2    example2    
2          no   =F3    example3
3         yes   123    example4
4          no   =F5    example5

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    使用布尔索引:

    m = df['state'].eq('no')
    
    df.loc[m, 'value'] = '-F'+df.index[m].astype(str)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-02
      • 2018-09-29
      • 1970-01-01
      • 2022-06-24
      • 2022-01-11
      • 1970-01-01
      • 2016-10-27
      相关资源
      最近更新 更多