无需使用Pandas将CSV列转换为排序后的列表列表
Got it, since you can't rely on Pandas, we can handle this entirely with basic Python operations. Let's walk through the process step by step:
Step 1: Parse the Raw Data
First, let's convert your flat CSV data into a list of floats (since your values are decimals):
raw_data = [1.0, 0.0, 5.0, 2.0, 0.0, 4.0, 3.0, 0.0, 3.0, 4.0, 0.0, 2.0, 5.0, 0.0, 1.0]
Step 2: Split Data into Columns
Your data is 5 rows × 3 columns, so we can extract each column using slice notation (start index, end index, step). For 3 columns, our starting indices are 0, 1, 2, and we step by 3 to grab every 3rd element:
# Extract each column col1 = raw_data[0::3] # First column: indices 0,3,6,9,12 col2 = raw_data[1::3] # Second column: indices 1,4,7,10,13 col3 = raw_data[2::3] # Third column: indices 2,5,8,11,14
Step 3: Sort Each Column
Now we sort each column as needed:
- Column 1: Sort in ascending order (default for
sorted()) - Column 2: All values are 0.0, so sorting won't change anything, but we can still run it for consistency
- Column 3: Sort in descending order using
reverse=True
# Sort columns sorted_col1 = sorted(col1) sorted_col2 = sorted(col2) sorted_col3 = sorted(col3, reverse=True)
Step 4: Combine into the Final List
Finally, wrap the sorted columns into a single list of lists:
OutputList = [sorted_col1, sorted_col2, sorted_col3] print(OutputList)
Output
Running this code will give you exactly the result you want:
[[1.0, 2.0, 3.0, 4.0, 5.0], [0.0, 0.0, 0.0, 0.0, 0.0], [5.0, 4.0, 3.0, 2.0, 1.0]]
If you need to read the data directly from a CSV file (instead of hardcoding the list), we can add a quick file-reading step too—just let me know!
内容的提问来源于stack exchange,提问作者Victor

