我試圖根據所有列的值來查找 DataFrame 中是否存在一行。我相信我找到了解決方案,但是在將 DataFrame 保存到/從 .csv 檔案中加載后我遇到了問題。
在下面的示例中,我遍歷 DataFrame 的每一行,并找到與每一行對應的索引——即所有列與被查詢行相同的行)。
注意:在我的真實代碼中,我遍歷一個較小的 DataFrame 并在一個較大的 DataFrame 中搜索行。但問題在這兩種情況下都會發生。
import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4]]) # Create data frame
df.to_csv(my_filename, index=False) # Save to csv
df1 = pd.read_csv(my_filename) # Load from csv
# Find original data in loaded data
for row_idx, this_row in df.iterrows():
print(np.where((df == this_row).all(axis=1))) # This returns the correct index
for row_idx, this_row in df.iterrows():
print(np.where((df1 == this_row).all(axis=1))) # This returns an empty index, and a FutureWarning
輸出是:
(array([0]),)
(array([1]),)
(array([], dtype=int64),)
(array([], dtype=int64),)
tmp.py:25: FutureWarning: Automatic reindexing on DataFrame vs Series comparisons is deprecated and will raise ValueError in a future version. Do `left, right = left.align(right, axis=1, copy=False)` before e.g. `left == right`
經過一番除錯,我發現從csv加載的DataFrame和原來的DataFrame不一樣:
# The DataFrames look identical, but comparing gives me a ValueError:
df
df1
df == df1
輸出是:
0 1
0 1 2
1 3 4
0 1
0 1 2
1 3 4
Traceback (most recent call last):
File "tmp.py", line 30, in <module>
df == df1
File "python3.9/site-packages/pandas/core/ops/common.py", line 69, in new_method
return method(self, other)
File "python3.9/site-packages/pandas/core/arraylike.py", line 32, in __eq__
return self._cmp_method(other, operator.eq)
File "python3.9/site-packages/pandas/core/frame.py", line 6851, in _cmp_method
self, other = ops.align_method_FRAME(self, other, axis, flex=False, level=None)
File "python3.9/site-packages/pandas/core/ops/__init__.py", line 288, in align_method_FRAME
raise ValueError(
ValueError: Can only compare identically-labeled DataFrame objects
- 注意:這似乎與類似的問題有關,但建議的解決方案,即指定索引標簽,并沒有解決我的問題。
提前致謝。
uj5u.com熱心網友回復:
如果您正在遍歷資料框,我建議您將 df 轉換為字典。
df_dict = df.to_dict('records')
這篇很棒的文章詳細介紹了它要快得多。
現在您可以列舉 df_dict 并將其與您想要的資料相匹配。
target_values = {'col1': 'foo', 'col2': 'bar', ...}
for i, row in enumerate(df_dict):
if row == target_values:
match_index = i
也許一個好主意是從僅匹配一列開始,如果匹配,檢查其他所有內容是否也相同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/433949.html
上一篇:Pandas:讀取帶有參考值的csv,逗號作為小數分隔符,句點作為數字分組符號
下一篇:將新行追加到CSV檔案
