如何从剪贴板读取固定宽度数据至Pandas DataFrame?
Great question! You absolutely can load fixed-width data from your clipboard straight into a Pandas DataFrame—here are a few reliable methods and alternatives to make this work smoothly:
Method 1: Use Pandas' Built-in read_clipboard() for Fixed-Width Data
Pandas has a handy read_clipboard() function that can handle fixed-width tables directly, especially if you let it auto-detect column boundaries. Just use sep=None (this tells the Python parsing engine to infer column separators, including strict fixed widths):
import pandas as pd # Load clipboard content directly into a DataFrame df = pd.read_clipboard(sep=None, engine='python')
This works perfectly for most standard fixed-width tables copied from apps like Excel, text editors, or database dashboards. If auto-detection misses the mark (e.g., columns have uneven spacing), you can manually define column positions using the colspecs parameter (the same as in pd.read_fwf):
# Example: Define exact start/end indices for each column df = pd.read_clipboard( sep=None, engine='python', colspecs=[(0, 8), (8, 16), (16, 24)] # Adjust these numbers to match your table's column widths )
Method 2: Manually Fetch Clipboard Text + pd.read_fwf
If you want more control (like preprocessing the text before parsing), you can first grab the clipboard content as a string, then feed it to pd.read_fwf() using a StringIO buffer.
First, install the lightweight pyperclip library (for cross-platform clipboard access) if you don't have it:
pip install pyperclip
Then use this code:
import pandas as pd import pyperclip from io import StringIO # Pull text directly from your clipboard clipboard_text = pyperclip.paste() # Convert the clipboard text into a DataFrame with fixed-width parsing df = pd.read_fwf(StringIO(clipboard_text)) # Add manual column specs if auto-detection isn't working df = pd.read_fwf( StringIO(clipboard_text), colspecs=[(0, 8), (8, 16), (16, 24)] )
Alternative: Fallback to delim_whitespace for Whitespace-Separated Fixed Widths
If your fixed-width table uses consistent whitespace between columns (instead of strict character counts), you can use delim_whitespace=True with read_clipboard() as a quick alternative:
df = pd.read_clipboard(delim_whitespace=True)
This is simpler but less precise for strictly fixed-width data where column spacing might vary.
Quick Note for Linux Users
Pandas' read_clipboard() relies on system tools for clipboard access on Linux. If it throws an error, install xclip (or xsel) first:
# For Debian/Ubuntu-based systems sudo apt-get install xclip # For Fedora/RHEL-based systems sudo dnf install xclip
内容的提问来源于stack exchange,提问作者Pavan

