gpt4 book ai didi

python - 将数据框中某个值选择的行替换为数据框中某个值选择的另一行

转载 作者:行者123 更新时间:2023-12-01 01:12:38 25 4
gpt4 key购买 nike

这是我的代码:

import pandas as pd
import numpy
from quilt.data.bussiere import test
ar = numpy.array([[1.1, 2, 3.3, 4], [2.7, 10, 5.4, 7], [5.3, 9, 1.5, 15]])
df = pd.DataFrame(ar, index = ['a1', 'a2', 'a3'], columns = ['A', 'B', 'C', 'D'])
df.loc[df['A'] == 5.3] = df.loc[df['A'] == 2.7]
df

结果是一行 NaN :

     A        B      C       D
a1 1.1 2.0 3.3 4.0
a2 2.7 10.0 5.4 7.0
a3 NaN NaN NaN NaN

如何正确更换?

最佳答案

pandas 对索引敏感,df.loc[df['A'] == 5.3]df.loc[df['A'] == 2.7]pandas object ,因此当您进行分配时会考虑 index ,因为其中之一是索引是a2,另一个是a3,这就是为什么你收到NaN

df.loc[df['A'] == 5.3] = df.loc[df['A'] == 2.7] .values # using value here,without the index match assign
df
Out[137]:
A B C D
a1 1.1 2.0 3.3 4.0
a2 2.7 10.0 5.4 7.0
a3 2.7 10.0 5.4 7.0

关于python - 将数据框中某个值选择的行替换为数据框中某个值选择的另一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54695426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com