gpt4 book ai didi

python - 使用数据帧另一部分的数据编辑 pandas 数据帧中的值

转载 作者:太空宇宙 更新时间:2023-11-03 18:17:44 24 4
gpt4 key购买 nike

我希望在 Pandas DataFrame 的一部分上使用索引来编辑值对应另一个索引。这是一个例子:

>>> from pandas import *
>>> from numpy.random import randn
>>> x = DataFrame(randn(3, 3), columns=[1, 2, 3], index=['a', 'b', 'c'])
>>> print x

1 2 3
a -1.007344 0.234990 0.772736
b 0.658360 1.330051 -0.269388
c 0.010871 1.035687 0.230169


>>> index1 = x.index[0:2]
>>> index2 = x.index[1:3]
>>> y = x
>>> x.loc[index1, 3] = x.loc[index2, 2]
>>> print x


1 2 3
a -1.007344 0.234990 NaN
b 0.658360 1.330051 1.330051
c 0.010871 1.035687 0.230169

后者的输出是相当意外的。相反,有效的方法如下:

>>> y.loc[index1, 3] = y.loc[index2, 2].values
>>> print y

1 2 3
a -1.007344 0.234990 1.330051
b 0.658360 1.330051 1.035687
c 0.010871 1.035687 0.230169

但是,后一种解决方案对于我想要使用的许多应用程序来说并不方便。例如我想写:

x.loc[index1, 3] = x.loc[index2, 2]+2 

x.loc[index1, 3] = x.loc[index1, 3] + x.loc[index2, 2]

等等

还有其他方法可以解决这个问题吗?

提前致谢!

最佳答案

Pandas 非常适合根据索引进行对齐。如果您考虑一下,“意外”结果实际上是可以理解的

x.loc[index1, 3]

作为带有索引标签['a', 'b']和赋值的系列

x.loc[index1, 3] = x.loc[index2, 2]

正在从 x.loc[index2, 2] 分配新值,这是一个带有索引标签 ['b', 'c'] 的系列。由于右侧的数据仅与左侧标签 'b' 处的系列对齐,因此该标签将获得新值,而标签 a 设置为 NaN,因为右侧没有该索引的值。

当您希望 Pandas 忽略索引时,您需要在右侧传递一个没有索引的对象。所以,正如你所展示的,

y.loc[index1, 3] = y.loc[index2, 2].values

产生所需的结果。

同样,对于更复杂的作业,您可以使用

x.loc[index1, 3] = x.loc[index2, 2].values + 2

x.loc[index1, 3] += x.loc[index2, 2].values

(请注意,第二个赋值使用就地加法运算符 +=。)

如果您有很多忽略索引的赋值,那么也许您应该使用 NumPy 数组而不是 Pandas DataFrame。

import pandas as pd
import numpy as np

x = pd.DataFrame(np.arange(9).reshape((3, 3)), columns=[1, 2, 3], index=['a', 'b', 'c'])
arr = x.values
print(arr)
# [[0 1 2]
# [3 4 5]
# [6 7 8]]

index1 = slice(0,2)
index2 = slice(1,3)
arr[index1, 2] = arr[index2, 1]
print(arr)
# [[0 1 4]
# [3 4 7]
# [6 7 8]]

# Instead of x.loc[index1, 3] = x.loc[index2, 2]+2
arr[index1, 2] = arr[index2, 1] + 2
print(arr)
# [[0 1 6]
# [3 4 9]
# [6 7 8]]

# Instead of x.loc[index1, 3] = x.loc[index1, 3] + x.loc[index2, 2]
arr[index1, 2] += arr[index2, 1]
print(arr)
# [[ 0 1 10]
# [ 3 4 16]
# [ 6 7 8]]

x.loc[:,:] = arr
print(x)
# 1 2 3
# a 0 1 10
# b 3 4 16
# c 6 7 8

关于python - 使用数据帧另一部分的数据编辑 pandas 数据帧中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24745302/

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