Python中从CSV文件获取表头并将字典列表转为Pandas DataFrame
Got you covered with both Python tasks! Let's break them down step by step:
You have two straightforward options here, depending on whether you prefer using the built-in csv module or Pandas:
Using the built-in csv module
This is great if you don't want to rely on external libraries:
import csv # Replace 'your_data.csv' with your actual file path with open('your_data.csv', 'r', encoding='utf-8') as csv_file: csv_reader = csv.reader(csv_file) # The first row of the CSV is the header row csv_headers = next(csv_reader) print("CSV Headers:", csv_headers)
Note: Add the encoding parameter if your CSV uses a specific character set (like utf-8 or latin-1) to avoid decoding errors.
Using Pandas (simpler for data workflows)
If you're already working with Pandas, this one-liner gets the job done:
import pandas as pd df = pd.read_csv('your_data.csv') # Convert the column names to a list for easy viewing csv_headers = df.columns.tolist() print("CSV Headers:", csv_headers)
For your provided cast data, creating the DataFrame is straightforward—you just need to specify your desired columns to ensure the structure matches what you need:
import pandas as pd # Your input list of dictionaries cast_records = [ {'cast_id': 1, 'character': 'W', 'credit_id': '5', 'gender': 2, 'id': 31, 'name': 'To', 'order': 0, 'profile_path': 'pQ'}, {'cast_id': 2, 'character': 'Bu', 'credit_id': '52', 'gender': 2, 'id': 12, 'name': 'Ti', 'order': 1, 'profile_path': 'uX'} ] # Define the exact columns you want (matches the keys in your dictionaries) target_columns = ['cast_id', 'character', 'credit_id', 'gender', 'id', 'name', 'order', 'profile_path'] # Create the DataFrame with the specified column order cast_df = pd.DataFrame(cast_records, columns=target_columns) # Verify the result print(cast_df)
This ensures your DataFrame uses only the columns you list, in the order you specify. If any dictionaries were missing a key from target_columns, Pandas would fill that cell with NaN (but your sample data has all keys covered, so you won't see that here).
内容的提问来源于stack exchange,提问作者Vlad Matao

