Okay, you are right, using .pipe() with your original convert_to_english_float function directly on a Pandas Series won't work as that function expects a single string, not a Series. Also, the .split(".")[0] part of your original convert_to_english_float function seems incorrect for standard Brazilian number format conversion (e.g., "1.234,56"). The typical conversion is to remove thousands separators (.) and replace the decimal separator (,) with a dot (.).
Let's implement the logic you described (.str.split(': r$').str[1]) and then apply the correct string replacement logic vectorially using .str methods, followed by pd.to_numeric.
import pandas as pd
# from IPython.display import clear_output # Not needed for the vectorized approach
# Assume df_gerais_principal and df_movimentos_orgao are already loaded DataFrames
# --- Step 1: Process df_movimentos_orgao to get sum of transfer values per process ---
# Filter rows where Description contains "valor transferido"
# Use .copy() to avoid potential SettingWithCopyWarning later
df_transfers = df_movimentos_orgao[
df_movimentos_orgao["Descrição"].str.contains("valor transferido", na=False)
].copy()
# Check if df_transfers is empty after filtering
if df_transfers.empty:
print("No 'valor transferido' entries found in df_movimentos_orgao.")
# Create an empty series for the groupby result to avoid errors later
sum_transferred_values_series = pd.Series(dtype=float)
else:
# Use str.split(': r$') to split the string. expand=True creates columns.
# Get the second element (index 1) which is the part after ': r$'
# The result is a Series of strings (or NaN if split failed)
value_strings_to_convert = df_transfers['Descrição'].str.split(': r$', expand=True)[1]
# Apply the Brazilian to English float conversion using vectorized string methods
# This replaces dots (thousands separators) with nothing and commas (decimal separators) with dots
# .str.replace handles potential NaNs gracefully (returns NaN if input is NaN)
cleaned_value_strings = value_strings_to_convert.str.replace('.', '', regex=False).str.replace(',', '.', regex=False)
# Convert the cleaned strings to numeric, coercing any errors (like non-numeric strings or NaNs) to NaN
df_transfers['transfer_value'] = pd.to_numeric(cleaned_value_strings, errors='coerce')
# Fill any resulting NaNs (either from split failure, string cleaning issue, or conversion failure) with 0.0
# Processes with no matching description or non-convertible value contribute 0 to the sum
df_transfers['transfer_value'] = df_transfers['transfer_value'].fillna(0.0)
# Group by 'Código Processo' and sum the extracted 'transfer_value'
# The result is a Series where the index is 'Código Processo' and values are the sums
sum_transferred_values_series = df_transfers.groupby("Código Processo")['transfer_value'].sum()
# --- Step 2: Convert the 'Valor' column in df_gerais_principal to float ---
# Apply the conversion using vectorized string methods followed by pd.to_numeric
df_gerais_principal['Valor_float'] = df_gerais_principal['Valor'].astype(str).str.replace('.', '', regex=False).str.replace(',', '.', regex=False)
# Convert to numeric, coercing any errors (like empty strings or leftover non-numeric chars) to NaN
df_gerais_principal['Valor_float'] = pd.to_numeric(df_gerais_principal['Valor_float'], errors='coerce')
# Fill NaNs that resulted from conversion errors with 0.0 (or decide on a different strategy)
# It's generally safer to fill with 0.0 if a missing original value should count as zero
df_gerais_principal['Valor_float'] = df_gerais_principal['Valor_float'].fillna(0.0)
# --- Step 3: Map the summed transferred values to df_gerais_principal and calculate ---
# Map the sum_transferred_values_series onto the 'Código Processo' column of df_gerais_principal
# This aligns the total transfer sum for each process back to the main DataFrame
# Processes in df_gerais_principal that are NOT found in sum_transferred_values_series
# (i.e., had no "valor transferido" entries in df_movimentos_orgao) will get NaN
transferred_sums_aligned = df_gerais_principal['Código Processo'].map(sum_transferred_values_series)
# Fill these NaN values (for processes with no transfers) with 0.0
transferred_sums_aligned = transferred_sums_aligned.fillna(0.0)
# Calculate the final column: initial Valor minus total transferred value
df_gerais_principal['valor_total_menos_transferidos'] = df_gerais_principal['Valor_float'] - transferred_sums_aligned
# Optional: Drop the temporary 'Valor_float' column if you don't need it
# df_gerais_principal = df_gerais_principal.drop(columns=['Valor_float'])
# Display head of relevant columns to verify
print(df_gerais_principal[['Código Processo', 'Valor', 'valor_total_menos_transferidos']].head())
# You can verify a specific row if needed
# Example:
# sample_codigo_to_check = df_gerais_principal['Código Processo'].iloc[0]
# print("\nVerification for a sample process:")
# print(df_gerais_principal[df_gerais_principal["Código Processo"].astype(str) == str(sample_codigo_to_check)][['Código Processo', 'Valor', 'Valor_float', 'valor_total_menos_transferidos']])