我想在 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(1)] #.index # if the indices are needed
输出:
A B C
3 10 11 12
或者,如果您有更多列并且想要忽略它们进行比较:
df[df[list(row)].eq(row).all(1)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句