You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pandas读取CSV后拆分列数据为列表的问题求助

Troubleshooting Empty Lists When Extracting Pandas DataFrame Columns

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 06:47:44