回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我试图替换pandas dataframe列中的字符串,这是成功的,但我缺少其他行,只有两个修改过的字符串及其行保留在DF中。剩下的一件事是根据第三列(Pos1,Pos3,Pos4)的数字对完整的DF进行排序
(参见所需输出)</p>
<p>代码:</p>
<pre><code>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)
</code></pre>
<pre><code>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
</code></pre>
<p>编辑:顺序/排序问题(不保留“内部”/“Pos1或Pos3”组中的确切顺序,但它是分散的)</p>
<p>图片:
<a href="https://i.stack.imgur.com/cgeM1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cgeM1.png" alt="enter image description here"/></a></p>
<p>如果你看这张图片,前10个项目的顺序应该与它从一开始的顺序完全相同,但即使是这些项目也没有顺序:它是无序的。它应该是:0,1,2,3,4,5,6,7。。10但不是0,9,7,6,5,8,3,2,1(这些都是“位置1”)</p>