How to Copy a NumPy Array to Clipboard through Python [3 Methods]

Do you want to copy a NumPy array to clipboard? In this Python blog, I will tell you how to copy a NumPy array to clipboard through Python using different methods with some illustrative examples.

To copy a NumPy array to the clipboard in Python, we can use several methods: employing pyperclip with np.array2string() for direct copying of array data, utilizing Pandas’ DataFrame.to_clipboard() for a more structured output, especially useful for Excel, or leveraging the OS module to interact with system clipboard commands after saving the array data to a temporary file.

Copy a NumPy Array to Clipboard through Python

Copying a NumPy array to the clipboard through Python is useful when we need to:

  • Share data quickly with non-Python users.
  • Transfer data to spreadsheet programs like Microsoft Excel or Google Sheets.
  • Facilitate data visualization in different software.

These are the reasons why we should copy a NumPy array to clipboard through Python.

There are three different ways to copy a NumPy array to clipboard through Python:

  1. Using pyperclip
  2. Using pandas dataframe with .to_clipbroad()
  3. Using os library

Let’s see them one by one using some illustrative examples:

1. NumPy array to the clipboard using pyerclip

Here, the np.array2string() function converts the array into a string format that the clipboard and the other applications can understand. Then the pyerclip is used to copy the string representation of the array to the clipboard.

This is how we can copy a NumPy array to clipboard through Python:

import numpy as np
import pyperclip

# Sample data: Daily average wind speeds (in mph) at weather stations in various states
wind_speeds = np.array([[10.5, 12.3, 7.8], [8.9, 11.2, 9.5], [14.1, 13.5, 10.2]])
stations = ["Station A (TX)", "Station B (CA)", "Station C (FL)"]
dates = ["2023-11-01", "2023-11-02", "2023-11-03"]

# Converting array to a string format using np.array2string
array_str = np.array2string(wind_speeds, separator=', ')
formatted_str = f"Daily Average Wind Speeds (mph) for {dates}:\n{array_str}"

# Copying to clipboard
pyperclip.copy(formatted_str)

Output:

Daily Average Wind Speeds (mph) for ['2023-11-01', '2023-11-02', '2023-11-03']:
[[10.5, 12.3,  7.8],
 [ 8.9, 11.2,  9.5],
 [14.1, 13.5, 10.2]]

Below is an image displaying the results of the code execution in the PyCharm environment.

how to copy a NumPy array to clipboard through Python

2. NumPy to clipboard copy values using Pandas dataframes

Pandas, a powerful data manipulation library in Python, can copy a NumPy array to the clipboard. This method is particularly useful if we’re already working within a Pandas workflow.

Steps:

  1. Convert the NumPy array to a Pandas DataFrame in Python.
  2. Use the .to_clipboard() method of the DataFrame.

Let’s take an example of using the dataframe to copy a NumPy array to clipboard through Python.

import numpy as np
import pandas as pd

data = np.array([[58, 77, 85], [30, 55, 75], [40, 60, 80]])
cities = ["Alaska", "Miami", "Chicago"]
months = ["January", "April", "July"]

df = pd.DataFrame(data, index=cities, columns=months)
df.to_clipboard(excel=True)

Output:

	January	April	July
Alaska	58	77	85
Miami	30	55	75
Chicago	40	60	80

The screenshot below showcases the output generated by running the code within the PyCharm editor.

numpy array to clipboard in Python

3. Copy NumPy array to clipboard after writing to a temporary file

If we’re dealing with very large arrays or prefer working with files, this method involves writing the array to a temporary file and then using system commands to copy its contents to the clipboard.

Steps:

  • Write the array to a temporary file.
  • Use a system command (like xclip on Linux, pbcopy on macOS, or clip on Windows) to copy the file content to the clipboard.
import numpy as np
import os

gdp_growth = np.array([2.3, 2.9, 2.2, -3.4, 4.1])

temp_file = "gdp_data.txt"
np.savetxt(temp_file, gdp_growth, header='U.S. GDP Growth Rates (2018-2022)', fmt='%.1f')

# For Windows
os.system(f"type {temp_file} | clip")

Output:

# U.S. GDP Growth Rates (2018-2022)
2.3
2.9
2.2
-3.4
4.1

The screenshot below visually represents the output from running the code in PyCharm.

numpy to clipboard in Python

Conclusion

There are different ways to copy a NumPy array to clipboard through Python, catering to diverse needs and scenarios. Whether it’s through the simplicity of pyperclip combined with np.array2string(), the structured approach of Pandas’ DataFrame.to_clipboard(), or the more system-integrated method using the OS module, each technique offers a unique blend of functionality and ease of use.

You may also like to read: