pandas: Copy DataFrame to the clipboard with to_clipboard()

Posted: | Tags: Python, pandas

The to_clipboard() method of pandas.DataFrame copies its contents to the clipboard. You can paste it directly to spreadsheets such as Excel or Numbers. It is very useful when used with IPython or Jupyter Notebook.

The read_clipboard() function is also provided to read the clipboard contents as DataFrame. See the following article.

It is also possible to save the contents of DataFrame directly to CSV or Excel file.

You can also work with the clipboard with pyperclip.

to_clipboard()

By default, the excel parameter is set to True, and the contents of DataFrame are copied to the clipboard separated by TAB \t.

It can be pasted directly into spreadsheets such as Excel and Numbers.

import pandas as pd

df = pd.DataFrame({'a': [0, 1, 2], 'b': [3, 4, 5]})
print(df)
#    a  b
# 0  0  3
# 1  1  4
# 2  2  5

df.to_clipboard()

#   a   b
# 0 0   3
# 1 1   4
# 2 2   5

If excel=False, the string displayed by print(df) is copied to the clipboard.

df.to_clipboard(excel=False)

#    a  b
# 0  0  3
# 1  1  4
# 2  2  5

You can also specify a delimiter character with the sep parameter.

df.to_clipboard(sep=',')

# ,a,b
# 0,0,3
# 1,1,4
# 2,2,5

Other parameters are common to the to_csv method.

Related Categories

Related Articles