我有一个 pandas DataFrame,其中包含来自 3D 测量的数据(约 27k 行)。我已经创建了一个由 3 个坐标列(x、y、z)组成的多索引。数据如下所示(沿 y 方向的多个 xz 平面):
Analog 1
Position Y Position X Position Z
y0 x0 z0 value0
y0 x0 z1 value1
y0 x0 z2 value2
y0 x1 z0 value3
y0 x1 z1 value4
y0 x1 z2 value5
y1 x0 z0 value6
y1 x0 z1 value7
y1 x0 z2 value8
y1 x1 z0 value9
y1 x1 z1 value10
y1 x1 z2 value11
这是一个示例:sample data
在下一步中,我想从每个其他 xz 平面中减去 y=y0
处的横截面/切片的值,以便标准化我的数据。目前,我通过循环每一行来做到这一点:
for row in data.itertuples():
ind = row[0]
value = row[1]
ref = data["Analog 1"].ix[(y0, ind[1], ind[2])]
data["Analog 1"].ix[ind] = value - ref
有没有更优雅的方式?
最佳答案
在我看来,reset_index
将索引值恢复为列然后调用 sub
会更容易。从感兴趣的行中减去所有行:
In [65]:
df = df.reset_index()
df.sub(df[df['Position Y'] == -27.0].iloc[0], axis=1)
Out[65]:
Position Y Position X Position Z Analog 1
0 0.0 0.0 0.0 0.00
1 0.5 0.0 0.0 0.00
2 1.0 0.0 0.0 0.00
3 1.5 0.0 0.0 0.00
4 2.0 0.0 0.0 -0.02
请注意,过滤 df[df['Position Y'] == -27.0]
返回一个 DataFrame
因此,如果您尝试减去它,它只会给出对于所有其他行,您NaN
,因此通过使用iloc[0]
索引第一行也是唯一一行,这将返回一个Series
,因此它将一起广播完整的 df。
如有必要,您可以稍后设置索引:
In [80]:
df = df.reset_index()
df = df.sub(df[df['Position Y'] == -27.0].iloc[0], axis=1)
df = df.set_index(df.columns[:3].tolist())
df
Out[80]:
Analog 1
Position Y Position X Position Z
0.0 0.0 0.0 0.00
0.5 0.0 0.0 0.00
1.0 0.0 0.0 0.00
1.5 0.0 0.0 0.00
2.0 0.0 0.0 -0.02
关于python - Pandas DataFrame 减去横截面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41550372/