我想在 pandas 框架内找到特定行(给定其所有列值)。 到目前为止我的尝试:
df = pd.DataFrame(
columns = ["A", "B", "C"],
data = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
])
# row to find (last one)
row = {"A" : 10, "B" : 11, "C" : 12}
# chain
idx = df[(df["A"] == 10) & (df["B"] == 11) & (df["B"] == 11)].index[0]
print(idx)
# iterative
mask = pd.Series([True] * len(df))
for k, v in row.items():
mask &= (df[k] == v)
idx = df[mask].index[0]
print(idx)
# pandas series
for idx in df.index:
print(idx, (df.iloc[idx,:] == pd.Series(row)).all())
有更简单的方法吗?类似于 idx = df.find(row) 的东西?
通常需要此功能,例如在时间序列中定位一个特定样本。我不敢相信没有直接的方法可以做到这一点。
最佳答案
你只是想要吗?
df[df.eq(row).all(axis=1)] #.index # if the indices are needed
输出:
A B C
3 10 11 12
或者,如果您有更多列并且想要忽略它们进行比较:
df[df[list(row)].eq(row).all(axis=1)]
关于python - 根据所有列值在 pandas 中选择一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72612597/