Of course! The reason slave.equals(master) is returning False is almost certainly because you are comparing the entire slave DataFrame against a filtered subset of the master DataFrame. They will have different numbers of rows, and thus can't be equal.
You are doing this:
slave_id = slave.loc[1, "frame_id"]: Get a single ID from the second row of slave.
master = master[master["frame_id"] == slave_id]: Filter master to only have rows with that ID.
slave.equals(master): Compare the original, unfiltered slave DataFrame with the new, filtered master DataFrame.
To do a correct comparison, you need to filter both DataFrames to contain only the data for the specific frame_id you want to compare.
Additionally, I've made some improvements to your pcd2array function to make it more robust and to avoid a potential issue where converting all columns to float can cause comparison problems with integer fields like frame_id.
Here is the complete, corrected, and enhanced code that will also print the specific differences if they exist.
Improved Code
from loguru import logger
import re
import numpy as np
import pandas as pd
def pcd2array_improved(path: str):
"""
Convert a PCD file to a pandas DataFrame.
This version avoids a global `.astype(float)` to preserve original data types (e.g., integers for IDs).
:param path: The save path of the PCD file.
:return: A pandas DataFrame with the point cloud data.
"""
try:
with open(path, "rb") as f:
res = f.read()
except FileNotFoundError:
logger.error(f"File not found at path: {path}")
return pd.DataFrame() # Return empty DataFrame on error
header_end_str = b'DATA binary'
try:
header_end_index = res.index(header_end_str)
header_text = res[:header_end_index].decode("utf-8")
header = header_text + "DATA binary"
# The actual binary data starts after the newline character following 'DATA binary'
data_start_index = header_end_index + len(header_end_str) + 1
binary_data = res[data_start_index:]
except ValueError:
logger.error("Could not find 'DATA binary' in the PCD file. It might be ASCII or corrupt.")
return pd.DataFrame()
# --- Header Parsing ---
try:
fields = re.search(r'FIELDS\s(.+)', header).group(1).strip().split()
sizes = [int(s) for s in re.search(r'SIZE\s(.+)', header).group(1).strip().split()]
types = re.search(r'TYPE\s(.+)', header).group(1).strip().lower().split()
points = int(re.search(r'POINTS\s(.+)', header).group(1).strip())
except AttributeError as e:
logger.error(f"Failed to parse PCD header: {e}. Check if FIELDS, SIZE, TYPE, or POINTS are missing.")
return pd.DataFrame()
if not all([fields, sizes, types, points]):
logger.error("PCD header is incomplete.")
return pd.DataFrame()
# --- Data Conversion ---
if len(binary_data) == 0 and points > 0:
logger.warning("PCD binary data is empty, but header indicates points exist.")
return pd.DataFrame(columns=fields)
# Create the structured dtype for numpy
dt_point_list = [f'{t}{s}' for t, s in zip(types, sizes)]
structured_dtype = np.dtype({
"names": fields,
"formats": dt_point_list,
})
# Read the binary buffer into a structured numpy array
data_array = np.frombuffer(binary_data, dtype=structured_dtype)
# Convert to pandas DataFrame. This preserves individual dtypes.
pcd_dataframe = pd.DataFrame(data_array)
# Your original code dropped the last column. This can be dangerous if the last
# column is actual data. It's often a 'padding' field from PCL.
# If you are sure the last column is unwanted padding, you can uncomment the next line.
# For now, we will keep it for a more accurate comparison.
# if pcd_dataframe.columns[-1] in ['_', 'padding']:
# pcd_dataframe = pcd_dataframe.drop(pcd_dataframe.columns[-1], axis=1)
return pcd_dataframe
def compare_dataframes(df1, df2, name1="Master", name2="Slave"):
"""
Compares two DataFrames and prints a detailed report of the differences.
"""
if df1.equals(df2):
print("✅ True: The DataFrames are identical.")
return
print("❌ False: The DataFrames are NOT identical. Analyzing differences...")
# 1. Compare Shapes
if df1.shape != df2.shape:
print(f"\n- Shape Mismatch:")
print(f" - {name1} shape: {df1.shape}")
print(f" - {name2} shape: {df2.shape}")
# 2. Compare Columns
if not df1.columns.equals(df2.columns):
print(f"\n- Column Mismatch:")
print(f" - {name1} columns: {df1.columns.tolist()}")
print(f" - {name2} columns: {df2.columns.tolist()}")
# Stop further comparison if columns are different, as it's a fundamental issue
return
# 3. Compare Data Types
if not df1.dtypes.equals(df2.dtypes):
print("\n- Dtype Mismatch:")
# Create a df to show dtype differences side-by-side
dtype_diff = pd.concat([df1.dtypes, df2.dtypes], axis=1, keys=[name1, name2])
# Show only rows where dtypes are different
print(dtype_diff[dtype_diff[name1] != dtype_diff[name2]])
# 4. Compare Values
try:
# Use pandas' compare function for a detailed, cell-by-cell comparison
# keep_equal=False shows only the differing values
# keep_shape=True would show NaNs for equal values, which can be verbose
diff = df1.compare(df2, keep_equal=False, align_axis=1)
if not diff.empty:
print(f"\n- Value Differences (showing up to 10):")
# We rename columns to make it clear which value belongs to which DataFrame
diff.columns = diff.columns.set_levels([name1, name2], level=1)
with pd.option_context('display.max_rows', 10, 'display.max_columns', None):
print(diff)
else:
# If diff is empty but .equals() was false, the issue is likely dtypes
print("\n- No value differences found. The inequality is likely due to different data types.")
except Exception as e:
print(f"\n- Could not perform value comparison. Error: {e}")
print(" (This can happen if indexes are not aligned despite resetting them).")
# --- Main Execution ---
# Use the improved function
master_df = pcd2array_improved("./2025-06-20-15-10_first.pcd")
slave_df = pcd2array_improved("./2025-06-20-15-10_second.pcd")
# Check if DataFrames were loaded successfully
if master_df.empty or slave_df.empty:
logger.error("One or both PCD files could not be loaded. Exiting.")
else:
# --- Correct Comparison Logic ---
# It's better to pick a frame_id that you know exists. Let's use the first one from the slave.
if "frame_id" in slave_df.columns and not slave_df.empty:
target_frame_id = slave_df.loc[0, "frame_id"]
print(f"--- Comparing data for frame_id: {int(target_frame_id)} ---\n")
# Filter BOTH dataframes for the specific frame_id
# Use .copy() to avoid SettingWithCopyWarning
master_filtered = master_df[master_df["frame_id"] == target_frame_id].copy()
slave_filtered = slave_df[slave_df["frame_id"] == target_frame_id].copy()
# Reset index on both for a fair comparison
master_filtered.reset_index(drop=True, inplace=True)
slave_filtered.reset_index(drop=True, inplace=True)
# Now, use the detailed comparison function
compare_dataframes(master_filtered, slave_filtered)
else:
logger.error("'frame_id' column not found or slave DataFrame is empty.")