使用Pandas读取CSV后拆分列数据为列表的问题求助
Hey there! Let's break down why your lists are coming up empty and fix this issue.
The Root Cause
When you run for col in df, you're actually iterating over the column names of your DataFrame—not the actual row values in each column. So col[0] is just grabbing the first character of the column name string (like the 't' in "time vector"), not the first data point in that column. That's why your lists aren't populated with the data you want.
Fixes: Multiple Ways to Extract Columns to Lists
1. The Simplest & Most Efficient Approach (Recommended)
You don't need a loop at all—Pandas has a built-in tolist() method to convert entire columns directly to lists. This is the fastest and most "Pandas-idiomatic" way:
# Assign columns directly to lists time = df['time vector'].tolist() untuned = df['untuned circuit response'].tolist() tuned = df['tuned circuit response'].tolist()
2. Using a Row Loop (For Learning or Custom Processing)
If you need to iterate through rows (e.g., for extra logic per row), use iterrows():
# First, initialize empty lists time = [] untuned = [] tuned = [] # Iterate over each row in the DataFrame for _, row in df.iterrows(): time.append(row['time vector']) untuned.append(row['untuned circuit response']) tuned.append(row['tuned circuit response'])
Note: iterrows() works well for small datasets but is slower than the first method for large data.
3. Using Column Positions (If You Don't Know Column Names)
If you prefer referencing columns by their index (0 for the first column, 1 for the second, etc.), use iloc:
time = df.iloc[:, 0].tolist() # All rows, first column untuned = df.iloc[:, 1].tolist() # All rows, second column tuned = df.iloc[:, 2].tolist() # All rows, third column
Why Your Original Code Failed
To recap: Your loop was looping through column names (strings) instead of data rows. Even if you initialized your lists, you'd be adding single characters from column names instead of actual numerical data. The fixes above target this core issue by accessing the column data directly.
内容的提问来源于stack exchange,提问作者Pete Howells

