[Python] Convert JSON object to Pandas DataFrame ensuring that Key is considered as column...

Discussão em 'Python' iniciado por Stack, Março 7, 2025.

  1. Stack

    Stack Membro Participativo

    I have a python script which needs to be executed by passing the input using command line. The command is as follows

    python script.py --input [{\\"A\\":\\"322|985\\",\\"B\\":3}]


    The idea is to convert the input to a pandas DataFrame. Code below does convert it to Pandas DataFrame but only creates a single column named 0 and the value for that column is [{\A\:\322|985\,\B\:3}].

    import json
    import pandas as pd
    import argparse


    def validate_input(input_data):

    if isinstance(input_data, pd.DataFrame):
    return input_data # Already a DataFrame, return as is

    json_conv = json.dumps(input_data)
    json_data = json.loads(json_conv)

    return pd.DataFrame([json_data]) # Convert JSON serializable to DataFrame

    def process_data(input_data):
    """
    Function that processes data, only called if dtype is valid.
    """
    validated_data = validate_input(input_data)
    print(validated_data)
    print("Processing data:\n", validated_data)

    def main():
    parser = argparse.ArgumentParser(description="Validate and process JSON or Pandas DataFrame input.")
    parser.add_argument("--input", type=str, help="Input data as a JSON string")
    args = parser.parse_args()

    try:
    process_data(args.input) # Proceed with processing only after validation
    except json.JSONDecodeError:
    raise TypeError("Invalid JSON input. Please provide a valid JSON string.")


    if __name__ == "__main__":
    main()



    Run code below to get expected output

    pd.DataFrame([{"A":"322|985","B":3}])

    Continue reading...

Compartilhe esta Página