Jupyter或终端中pd.read_clipboard()无法使用,报错AttributeError
pd.read_clipboard() AttributeError Hey there, let's tackle this frustrating issue with pd.read_clipboard()! The error you're hitting stems from a mismatch between the data type your clipboard returns and what older pandas versions expect.
What's Causing the Error?
Looking at your traceback, the line text = text.decode('UTF-8') is throwing the AttributeError. In Python 3, the clipboard_get() function might already return a string (str) instead of raw bytes. When you try to call .decode() on a string (which doesn't have this method), pandas throws this error. This is a bug that's been fixed in newer pandas releases.
Solutions to Try
1. Upgrade Pandas (Recommended)
The simplest and most permanent fix is to update your pandas to a version where this issue is resolved. Run one of these commands depending on your package manager:
# Using pip pip install --upgrade pandas # Using conda (if you're on Anaconda/Miniconda) conda update pandas
2. Temporary Workaround (If You Can't Upgrade)
If upgrading isn't an option right now, you can manually handle the clipboard content before passing it to pandas:
import pandas as pd from pandas.io.clipboard import clipboard_get from pandas.io.common import StringIO # Get clipboard content text = clipboard_get() # Decode only if it's bytes (skip if it's already a string) if isinstance(text, bytes): text = text.decode('UTF-8') # Read the text as a table, just like read_clipboard does nfl_frame = pd.read_table(StringIO(text))
3. Patch the pandas Clipboard File (Advanced)
If you want to fix the underlying code in your current pandas installation:
- Navigate to the clipboard.py file at
/home/aditya/anaconda3/lib/python3.5/site-packages/pandas/io/clipboard.py(from your traceback) - Find the line
text = text.decode('UTF-8') - Replace it with this check to handle both bytes and string types:
if isinstance(text, bytes): text = text.decode('UTF-8')
This way, pandas will only try to decode the text if it's actually bytes, avoiding the AttributeError entirely.
内容的提问来源于stack exchange,提问作者Aditya Chandel

