【解決方法】複数の操作からのデータフレームの変更された行を単一のリストに連結する


データフレームの列の値をユーザーが選択した値に置き換える関数を作成しました。 コードは複数の入力を受け入れます。

郵便配達員ペイロードによる入力の例-

Python
{"Filepath":"C:/Users/shootings.csv","Operand":[{"OperationName":"replaceColumnValue","Details":[{"ColumnName":"armed","ExistingValue":"gun","ReplacingValue":"Not knooooooooooooooooown"},{"ColumnName":"manner_of_death","ExistingValue":"shot","ReplacingValue":6666666666666666666666666666666666666666666666666666666666}]}]}

私が試したこと:

私のコード:

# Replacing the value of a column
def replace_fun(df, replace_inputs):
    try:
        col_name = replace_inputs["ColumnName"]
        col_value = str(replace_inputs["ExistingValue"])
        replace_value = str(replace_inputs["ReplacingValue"])
        
        # Check if column name exists in the dataframe
        if col_name not in df.columns:
            raise HTTPException(status_code=400, detail=f"Column {col_name} doesn't exist in the dataset")
        
        # Check if column value exists in the dataframe
        if col_value not in df[col_name].astype(str).values:
            raise HTTPException(status_code=400, detail=f"Column value {col_value} doesn't exist in the column {col_name}")
        
        modified_rows = df[col_name].astype(str) == col_value
        df.loc[modified_rows, col_name] = replace_value
        modified_data = df[modified_rows].to_dict(orient='records')
        
        for record in modified_data:
            for key, value in record.items():
                if isinstance(value, float):
                    record[key] = str(value)
        
        return modified_data
    
    except HTTPException as e:
        logging.error(f"An error occurred while performing the operation: {str(e)}")
        raise e
    

def cleaning_and_analysis(filepath, operation=None, raw_data=None):
csv_dataframe = pd.read_csv(filepath, encoding='utf-8')

result = {}

上記のコードは、単一のリストで複数の入力の変更された行を返すことになっています。 また、複数の入力間で共通の変更された行がある場合、その行は更新された値で 1 回だけ返されます。

私の出力と問題: 現在のコードでは、変更されたすべての行が返されません。 以前の入力更新 (存在する場合) と共に最後の入力の変更された行を返しますが、入力 2 に存在しない変更された行が入力 1 にある場合、その行は返されません。

解決策を教えてください。

ノート: さらに説明が必要な場合は、コメントを残してください。

コメント

タイトルとURLをコピーしました