Pandas 根据条件重命名所有连续的行
Pandas renaming all consecutive rows based on condition
我有类似的数据框:
您可以使用此代码重新创建它:
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" 的值更改为大于 10 的 "col_2" 或 "col_3"。
因此,如果 "col_2" 或 "col_3" 中的数字大于 10,则应重命名直到下一个大于 10 的数字的所有行。
最终应该是这样的:
你可以用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
我有类似的数据框:
您可以使用此代码重新创建它:
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" 的值更改为大于 10 的 "col_2" 或 "col_3"。
因此,如果 "col_2" 或 "col_3" 中的数字大于 10,则应重命名直到下一个大于 10 的数字的所有行。
最终应该是这样的:
你可以用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