我有一个带有六个不同标签的数据框:presence
、x
、y
、vx
、vy
和 lane
。我想区分一系列列上的两个行索引 [x
, y
, vx
, vy
]。然而,减法给出了 NaN
。感谢您的帮助。
import pandas as pd
data = {'presence': [1, 1, 0, 1],
'x': [17, 35, 46, 57],
'y': [4, 4, 8, 0],
'vx': [2, 5, 9, 12],
'vy': [0.3, 0.5, 0.2, 0],
'lane': [0, 1, 2, 0]}
df = pd.DataFrame(data)
a = df.iloc[[2]]
b = df.iloc[[1]]
diff_x = b[['x','y']] - a[['x','y']] # Gives two rows and two columns of nan
# Expected output: 11 4
最佳答案
这是因为您将 a 和 b 提取为 DataFrame
而不是系列,
a
Out[312]:
presence x y vx vy lane
2 0 46 8 9 0.2 2
b
Out[313]:
presence x y vx vy lane
1 1 35 4 5 0.5 1
上面的dataframe index
是不同的,当我们进行计算时pandas
会首先检查index
,如果index不匹配那么输出将是NaN
快速修复:
diff_x = b[['x','y']].values - a[['x','y']].values
diff_x
Out[311]: array([[-11, -4]], dtype=int64)
关于python - 在pandas dataframe python中减去两行的一系列列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63691280/