Python 仅替换同一列中的某些行
给定一列:Python 仅替换同一列中的某些行,python,pandas,dataframe,Python,Pandas,Dataframe,给定一列: name Jules Jules Jules Jules Vince 我只需要用Jules的上半部替换Quentin 例如: name Quentin Quentin Jules Jules Vince 如何仅替换给定列中的某些值 更进一步地说,朱尔斯的位置将永远不会相同 我曾考虑过这样迭代,但没有成功: countOfJules = df['name'].value_counts()['Jules'] halfLenght = int(countoftbd/2) liste
name
Jules
Jules
Jules
Jules
Vince
我只需要用Jules的上半部替换Quentin
例如:
name
Quentin
Quentin
Jules
Jules
Vince
如何仅替换给定列中的某些值
更进一步地说,朱尔斯的位置将永远不会相同
我曾考虑过这样迭代,但没有成功:
countOfJules = df['name'].value_counts()['Jules']
halfLenght = int(countoftbd/2)
listed = df['name'].to_list()
counter = 1
for eachname in listed:
if eachname == 'Jules' and counter <= halfLenght:
listed[:] == 'Quentin'
counter += 1
这相当简单:
# where name is Jules
is_jules = df['name'].eq('Jules')
# total `Jules` in `name`
num_jules = is_jules.sum()
# first half `Jules`
first_half = is_jules.cumsum().le(num_jules//2)
df.loc[is_jules & first_half, 'name'] = 'Quentin'
输出:
name
0 Quentin
1 Quentin
2 Jules
3 Jules
4 Vince
通常用于访问数组或列表、数据帧等的子集的术语是切片。以及访问数据帧的特定成员的其他方式。在您的情况下,看起来您是根据数组中的索引进行选择的,在这种情况下,您可以使用df[start:stop],其中start和stop是您想要访问的索引