如何使用Python将浮点型变量保存至Excel(.xlsx)的不同列中
Hey there! Let's fix this issue for you. Since CSV and XLSX are different file formats, the code that works for CSV won't directly translate to XLSX—no worries, though, we've got two straightforward solutions using popular Python libraries that'll get your variables a, b, c into separate columns of an XLSX file in no time.
Solution 1: Using Pandas (Recommended for Simplicity)
Pandas makes this super easy, even for beginners. First, you'll need to install it if you haven't already:
pip install pandas openpyxl
(Openpyxl is a dependency Pandas uses to write XLSX files.)
Then, here's the code:
import pandas as pd # Replace these with your actual variable data a = [1, 2, 3, 4] b = ["apple", "banana", "cherry", "date"] c = [True, False, True, False] # Create a DataFrame where each variable maps to a column df = pd.DataFrame({ 'Column A': a, 'Column B': b, 'Column C': c }) # Save to XLSX—index=False skips adding extra row numbers df.to_excel('output.xlsx', index=False)
- Feel free to rename
'Column A','Column B','Column C'to whatever headers you want. - If you want to keep row numbering, just remove the
index=Falseargument.
Solution 2: Using Openpyxl (Direct Excel Manipulation)
If you'd rather work directly with Excel files without Pandas, openpyxl is a solid choice. Install it first:
pip install openpyxl
Here's the code to get your variables into separate columns:
from openpyxl import Workbook # Replace with your actual variable data a = [1, 2, 3, 4] b = ["apple", "banana", "cherry", "date"] c = [True, False, True, False] # Create a new workbook and select the default sheet wb = Workbook() ws = wb.active # Add column headers (optional but helpful for readability) ws.append(['Column A', 'Column B', 'Column C']) # Loop through paired values from each variable and add rows for val_a, val_b, val_c in zip(a, b, c): ws.append([val_a, val_b, val_c]) # Save the final workbook wb.save('output.xlsx')
- Make sure your variables
a,b,care the same length—if not, you'll need to handle missing values (like filling inNonefor gaps) before usingzip().
Both methods will generate an XLSX file where each variable lives in its own column, just like you need. The key difference from CSV is that XLSX isn't a plain-text format, so we need specialized libraries instead of Python's built-in csv module.
内容的提问来源于stack exchange,提问作者Patrick

