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

熊猫根据条件重命名所有连续行

  •  0
  • user7086216  · 技术社区  · 8 年前

    我有类似的数据框架:

    enter image description here

    您可以使用以下代码重新创建它:

    import pandas as pd
    df = pd.DataFrame({
        'A' : 1.,
        'name' :  pd.Categorical(["hello","hello","hello","hello"]),
        'col_2' : pd.Categorical(["2","2","12","Nan"]),
        'col_3' : pd.Categorical(["11","1","3","Nan"])})
    

    我想将每行中“name”的值更改为“col\u 2”或“col\u 3”大于10。

    因此,如果“col\u 2”或“col\u 3”中有一个大于10的数字,则应重命名下一个大于10的数字之前的所有行。

    下面是它最终的样子:

    enter image description here

    1 回复  |  直到 8 年前
        1
  •  0
  •   Mr Tarsa    8 年前

    您可以通过 cumsum

    name_index = df[['col_2', 'col_3']]\
        .apply(pd.to_numeric, errors='coerce')\ 
        .ge(10)\
        .any(axis=1)\
        .cumsum()
    df['name'] = df['name'].astype(str) + '_' + name_index.astype(str)
    print(df)
    
        A    col_2  col_3   name
    0   1.0  2      11      hello_1
    1   1.0  2      1       hello_1
    2   1.0  12     3       hello_2
    3   1.0  NaN    NaN     hello_2