Skip to content

Instantly share code, notes, and snippets.

@secemp9
Last active November 17, 2022 13:14
Show Gist options
  • Save secemp9/d1197f5bbf797f303e6bdc7049898a7c to your computer and use it in GitHub Desktop.
Save secemp9/d1197f5bbf797f303e6bdc7049898a7c to your computer and use it in GitHub Desktop.
panda copy/paste dataframe using clipboard
# using https://stackoverflow.com/a/68032799/12349101 and https://stackoverflow.com/a/101167/12349101
import win32clipboard
import pandas as pd
# set clipboard data
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(""" 0 1 2
level1 level2
foo a 0.518444 0.239354 0.364764
b 0.377863 0.912586 0.760612
bar a 0.086825 0.118280 0.592211""")
win32clipboard.CloseClipboard()
# get clipboard data
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print(data)
def str2frame(estr, sep = ',', lineterm = '\n', set_header = True):
dat = [x.split(sep) for x in estr.split(lineterm)][1:-1]
df = pd.DataFrame(dat)
if set_header:
df = df.T.set_index(0, drop = True).T # flip, set ix, flip back
return df
print(str2frame(data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment