我正在尝试替换 Pandas 数据框列中的字符串,这是成功的,但我缺少其他行,只有两个修改后的字符串及其行保留在 DF 中。剩下的一件事是通过第三列(Pos1、Pos3、Pos4)中的数字对完整的 DF 进行排序 (见所需的输出)。
代码:
df = pd.DataFrame({'1': [5614,4564,3314,3144,1214,4314],
'2': ['banana','kiwi' ,'salsa','avocado','mix','juice'],
'3': ['Pos1','Pos1','Pos3','Pos3','Pos1','Pos1']
})
df = df[4:5].replace('Pos1', 'Pos3')
# however this doesn't modify the original df but overwrites it with only two rows ( 1214 mix Pos3, 4314 juice Pos3)
# regarding to locate the integers from 3rd column:
for indx,row in df.iterrows():
if row[3].isdigit() == True:
#... sort_by(row[3])
# but preserve the following order (check desired output)
Dataframe
1 2 3
0 5614 banana Pos1
1 4564 kiwi Pos4
2 3314 salsa Pos3
3 3144 avocado Pos3
4 1214 mix Pos1
5 4314 juice Pos1
Desired output:
1 2 3
0 5614 banana Pos1
1 3314 salsa Pos3
2 3144 avocado Pos3
3 1214 mix Pos3
4 4314 juice Pos3
5 4564 kiwi Pos4
编辑:排序/排序问题(不保留“内部”/Pos1 或 Pos3 组的确切顺序,但它相当分散)
如果您查看图片,前 10 个项目的顺序应该与从一开始时完全相同,但即使是这些也不是按顺序排列的:它被打乱了。它应该是:0,1,2,3,4,5,6,7.. 10 但不是 0,9,7,6,5,8,3,2,1(这些都是“Pos1”)< /p>
答案 0 :(得分:0)
这是否回答了您的问题?
df = pd.DataFrame({'1': [5614,4564,3314,3144,1214,4314],
'2': ['banana','kiwi' ,'salsa','avocado','mix','juice'],
'3': ['Pos1','Pos4','Pos3','Pos3','Pos1','Pos1']
})
# replace strings only in column 3
df.loc[4:, '3'] = df.loc[ 4:,'3'].replace('Pos1', 'Pos3')
# sort values by column '3'
df = df.sort_values('3')
df
>>>
1 2 3
0 5614 banana Pos1
2 3314 salsa Pos3
3 3144 avocado Pos3
4 1214 mix Pos3
5 4314 juice Pos3
1 4564 kiwi Pos4
这将替换 '3' 中所有大于 4 的 indecwes 的所有字符串。稍后按此列排序(不重新索引)。
如果您希望索引保持不变,则必须使用 df = df.sort_values('3', ignore_index=True)
进行排序。
更新
如果要在索引大于 3 后对 DataFrame 进行排序,则必须先切片,然后排序并替换值。可以看起来像这样。
df.loc[3:] = df.loc[3:].sort_values('3').set_index(df.loc[3:].index)
调用 set_index
很重要,因为如果您不这样做,右侧会再次从 0
开始,您将使用 NaN 值填充 DataFrame。
答案 1 :(得分:0)
替换行应该是:
df[4:5] = df[4:5].replace('Pos1', 'Pos3')
您的原始代码的问题在于它仅将 [4:5] 传递给 df。