Pandas根据条件重命名所有连续的行

时间:2017-12-25 20:24:11

标签: python python-3.x pandas cumsum

我的数据框类似于:

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_2"或" col_3"高于10.

所以,如果" col_2"中有一个高于10的数字。或者在" col_3"中,应重命名直到下一个高于10的数字的所有行。

最后它应该是什么样子:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用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
相关问题