簡體   English   中英

保存加載后的ValueError pandas DataFrame to csv

[英]ValueError after saving and loading pandas DataFrame to csv

我試圖根據所有列的值查找 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

output 是:

(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

output 是:

   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
  • 注意:這似乎與類似的問題有關,但建議的解決方案,即指定索引標簽,並沒有解決我的問題。

提前致謝。

如果您正在遍歷數據框,我建議您將 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

也許一個好主意是從僅匹配一列開始,如果匹配則檢查其他所有內容是否也相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM