Python Jupyter: Shortcut to copy output of a cell - python

Please see attached screenshot:
In Jupyter Python: Is there a shortcut to copy the output of a cell to clipboard? (ie without having to manually select and ctrl-c?)
Alternatively is there a python function that instead of print would return its output directly in the clipboard for it to be pasted later?

You may use the following piece of code:
import pandas as pd
df = pd.DataFrame(['Copy me to clipboard'])
df.to_clipboard(index=False,header=False)

what i have done is ---file -->Print Preview , it opens the whole output in another tab than you can copy whatever you want

Related

How to save python notebook cell code to file in Colab

TLDR: How can I make a notebook cell save its own python code to a file so that I can reference it later?
I'm doing tons of small experiments where I make adjustments to Python code to change its behaviour, and then run various algorithms to produce results for my research. I want to save the cell code (the actual python code, not the output) into a new uniquely named file every time I run it so that I can easily keep track of which experiments I have already conducted. I found lots of answers on saving the output of a cell, but this is not what I need. Any ideas how to make a notebook cell save its own code to a file in Google Colab?
For example, I'm looking to save a file that contains the entire below snippet in text:
df['signal adjusted'] = df['signal'].pct_change() + df['baseline']
results = run_experiment(df)
All cell codes are stored in a List variable In.
For example you can print the lastest cell by
print(In[-1]) # show itself
# print(In[-1]) # show itself
So you can easily save the content of In[-1] or In[-2] to wherever you want.
Posting one potential solution but still looking for a better and cleaner option.
By defining the entire cell as a string, I can execute it and save to file with a separate command:
cell_str = '''
df['signal adjusted'] = df['signal'].pct_change() + df['baseline']
results = run_experiment(df)
'''
exec(cell_str)
with open('cell.txt', 'w') as f:
f.write(cell_str)

How to refresh all pivot table of an excel file using Python xlwings [duplicate]

I am trying to refresh a pivot table in excel upon data written by XLWINGS.
As I don't know how to do it directly from XLWINGS, I tried to use VBA.
Let's split my process in 2 steps:
Step1
I launch the python code from vba (my module name is "PosRep", the python code writtes back a range of data in a specified sheet thanks to xlwings.
Sub launchPython()
RunPython ("import PosRep; PosRep")
End Sub
Step 2
But as I don't know in advance the size of my newly created Range in Excel, I want to select it, add a new Name (NamedRange) and refresh my pivot (already linked to the NamedRange).
Sub SelectRange()
Worksheets("GPODump").Range("A1").Select
'...
End Sub
Both Subs work independently well. But I cannot manage to make them work in a raw. The following code:
Sub Main()
launchPython
SelectRange
End Sub
produces a VBA error "Select method of Range class failed" on the statement:
Worksheets("GPODump").Range("A1").Select
I presume there is a conflict with the XLWINGS VBA module but I can't figure out what it can be...
Anyone's help would be more than welcome !
Thx
The problem came from the VBA code. The following code works fine:
Sheets("GPODump").Select
Sheets("GPODump").Range("A1").Select
Maybe it's too late but you can do it within xlwings - this is what worked for me:
import xlwings as xw
# open excel App
app_excel = xw.App(visible = False)
# open the excel file, select the tab and the PivotTable to refresh
wbook = xw.Book( 'YourFile.xlsx' )
wbook.sheets['Tab1'].select()
wbook.api.ActiveSheet.PivotTables('PivotTableName').PivotCache().refresh()
I was looking how to solve this for Mac, here is how I did to refresh all pivot tables and etc:
wb.api.active_sheet.refresh_all(wb.api)
Hopes that this saves someone else time. Took me a while to figure it out.

Looping through ipynb files in python

So if I have the same piece of code inside of 10 separate .ipynb files with different names and lets say that the code is as follows.
x = 1+1
so pretty simple stuff, but I want to change the variable x to y. Is their anyway using python to loop through each .ipynb file and do some sort of find and replace anywhere it sees x to change it or replace it with y? Or will I have to open each file up in Jupiter notebook and make the change manually?
I never tried this before, but the .ipynb files are simply JSONs. These pretty much function like nested dictionaries. Each cell is contained within the key 'cells', and then the 'cell_type' tells you if the cell is code. You then access the contents of the code cell (the code part) with the 'source' key.
In a notebook I am writing I can look for a particular piece of code like this:
import json
with open('UW_Demographics.ipynb') as f:
ff = json.load(f)
for cell in ff['cells']:
if cell['cell_type'] == 'code':
for elem in cell['source']:
if "pd.read_csv('UWdemographics.csv')" in elem:
print("OK")
You can iterate over your ipynb files, identify the code you want to change using the above, change it and save using json.dump in the normal way.

Python vba extract to get bin of macro

I am trying to add a vba_project to "Sheet1" of a workbook using python.
I am following XLSXWRITER documentation to get the bin of the VBA code from a different sheet which I would want to use in "Sheet1" of my new workbook.
I enter the below code in command prompt but I get the error: "'vba_extract.py' is not recognized as an internal or external command"
$ vba_extract.py Book1.xlsm
Extracted: vbaProject.bin
Can someone give me a step by step on how to extract the macro from old file as bin and then input into sheet1 of new workbook using python?
You have to tell the cmd you're running a python file.
Try this batch code:
cd C:\path\of\yourfile.py
python vba_extract.py Book1.xlsm
edit:
Added cd command, you have to be in the folder of the python file.
I figured this out today and just wanted to leave it here for any future people to use. This was so unbelievably frustrating to figure out how to do. If you are using the Pandas library, this is also relevant. Make sure to install xlsxwriter also.
1.Click on your windows start button and type 'cmd' and click on it to run the Command Prompt.
2.Once you have it open, you need to locate where the vba_extract.py file is. For me it was here:
C:\Users\yourusername\AppData\Local\Programs\Python\Python36-32\Scripts\vba_extract.py
3.Now, you need to get the path of the .xlsm file you want to take from. If you don't have a .xlsm file made. Make one. Here is an example:
C:\Users\yourusername\Desktop\excelfilename.xlsm
4.Now, back to the Command Prompt. This is exactly what you will type. You will take both items from steps 2 and 3 and combine then and hit enter. Here:
C:\Users\yourusername\AppData\Local\Programs\Python\Python36-32\Scripts\vba_extract.py C:\Users\yourusername\Desktop\excelfilename.xlsm
if it is successful, it will tell you this:
Extracted: vbaProject.bin
5.For this one I'm not sure. I assume that wherever your .xlsm file is where the .bin file will end up. For this example, it ended up on my desktop. It will have all the macros you created or had on the original .xlsm file.
C:\Users\yourusername\Desktop/vbaProject.bin
Here is an example of it being used in full code:
import pandas
import xlsxwriter
df_new = pd.read_csv('C:\\Users\\yourusername\\Desktop\\CSV1.csv')
writer = pd.ExcelWriter('C:\\Users\\yourusername\\Desktop\\CSV1.xlsx')
df_new.to_excel(writer, index = False, sheet_name = 'File Name', header = False)
pandaswb = writer.book
pandaswb.filename = 'C:\\Users\\yourusername\\Desktop\\newmacroexcelfile.xlsm')
pandaswb.add_vba_project(r'C:\Users\yourusername\Desktop/vbaProject.bin')
writer.save()

IPython Notebook output cell is truncating contents of my list

I have a long list (about 4000 items) whose content is suppressed when I try to display it in an ipython notebook output cell. Maybe two-thirds is shown, but the end has a "...]", rather than all the contents of the list. How do I get ipython notebook to display the whole list instead of a cutoff version?
pd.options.display.max_rows = 4000
worked for me
See : http://pandas.pydata.org/pandas-docs/stable/options.html
I know its a pretty old thread, but still wanted to post my answer in the hope it helps someone.
You can change the number of max_seq_items shown by configuring the pandas options as follows:
import pandas as pd
pd.options.display.max_seq_items = 2000
This should work:
print(str(mylist))
Simple!
How to disable list truncation in IPython:
Create an IPython config file if you don't already have one:
ipython profile create
Edit the config file to include this line:
c.PlainTextFormatter.max_seq_length = 0
Restart your notebook instance.
The following line prints everything in your list in a readable manner.
[print(x) for x in lis]
A quick hack if you're using pandas is to do
from pandas import DataFrame
from IPython.display import HTML
HTML(DataFrame(myList).to_html())
For cases where the output of print(mylist) is something like [1, 1, 1, ..., 1, 1, 1] then [*mylist] will expand the items into rows where all items are visible.
Here's a way to display the whole list in the IPython output cell that doesn't require Pandas:
from IPython.display import HTML
x = range(4000)
HTML('<br />'.join(str(y) for y in x))
It is also pretty easy to add additional HTML elements and get a more elaborate display. Clicking to the left of the output cell will now shrink the contents and add a local scroll bar.
just use the print command instead of calling the list directly. Like print mylist . It would not truncate then.

Categories

Resources