Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 根据条件重命名所有连续行_Python_Python 3.x_Pandas_Cumsum - Fatal编程技术网

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

Python 根据条件重命名所有连续行,python,python-3.x,pandas,cumsum,Python,Python 3.x,Pandas,Cumsum,我有类似的数据帧: 您可以使用以下代码重新创建它: 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"])})

我有类似的数据帧:

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

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"])})
我想更改每行中“col_2”或“col_3”大于10的“name”值

因此,如果在“col_2”或“col_3”中有一个大于10的数字,则应重命名下一个大于10的数字之前的所有行

下面是它最后的样子:

你可以通过


为什么要使用pd.category?@AntonBR我同意你的看法,但只有在输入数据中不包含“Nan”字符串的情况下:)很好!我冒昧地做了一些小改动(pd.to_numeric)和.ge(),哇,我没有注意到
errors='concurve'
。现在看起来好多了。谢谢,太好了。非常感谢你!
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