Archive for the ‘Python / SciPy / pandas’ Category.
2021-01-16, 20:49
Ich habe heute auf einer meiner Linux-Maschinen Jupyter Notebook installiert. Um die — für die Arbeit im lokalen Netz lästigen — Sicherheitsabfragen zu umgehen, habe ich mir ausgehend von https://stackoverflow.com/questions/41159797/how-to-disable-password-request-for-a-jupyter-notebook-session ein kleines Startskript geschrieben:
#! /bin/bash
jupyter notebook --ip='*' --NotebookApp.token='' --NotebookApp.password='' |
#! /bin/bash
jupyter notebook --ip='*' --NotebookApp.token='' --NotebookApp.password=''
Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined.
Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.
More Posts - Website
2021-01-16, 20:45
Mit cudf gibt es ein Paket, das pandas Datenstrukturen auf nvidia-Grafikkarten verarbeiten kann. Einen i7 3770 mit 24 GB RAM habe ich jetzt mit einer CUDA-fähigen Grafikkarte (Typ Quadro P400) ausgestattet, damit ich damit rumspielen arbeiten kann. Unter https://towardsdatascience.com/heres-how-you-can-speedup-pandas-with-cudf-and-gpus-9ddc1716d5f2 findet man passende Beispiele, diese habe ich in einem Jupyter-Notebook laufenlassen.

Ein Geschwindigkeitszuwachs ist erkennbar, insbesondere bei der Matrix-Größe aus dem verlinkten Beispiel war die CUDA-Variante mehr als 3x so schnell wie die CPU-Variante. Das Merge mit der vollen Matrix-Größe lief bei mir leider nicht, da limitieren vermutlich die 2 GB RAM, die die P400 bietet.
Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined.
Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.
More Posts - Website
2021-01-10, 19:19
Im letzten Beitrag hatten wir mit hue
die Zugehörigkeit der Iris Data Orchideen dargestellt, Seaborn besitzt aber mit style
und size
noch weitere Möglichkeiten der Unterscheidung. style
nutzt dabei verschiedene Symbole, size
unterschiedliche Punktgrößen. Die verschiedenen Optionen können auch kombiniert werden.
import seaborn as sns
sns.set(style = "darkgrid")
iris=sns.load_dataset('iris')
sns.scatterplot(
x=iris['sepal_width'],
y=iris['sepal_length'],
style=iris['species'],
legend=False
) |
import seaborn as sns
sns.set(style = "darkgrid")
iris=sns.load_dataset('iris')
sns.scatterplot(
x=iris['sepal_width'],
y=iris['sepal_length'],
style=iris['species'],
legend=False
)

import seaborn as sns
sns.set(style = "darkgrid")
iris=sns.load_dataset('iris')
sns.scatterplot(
x=iris['sepal_width'],
y=iris['sepal_length'],
size=iris['species'],
legend=False
) |
import seaborn as sns
sns.set(style = "darkgrid")
iris=sns.load_dataset('iris')
sns.scatterplot(
x=iris['sepal_width'],
y=iris['sepal_length'],
size=iris['species'],
legend=False
)

import seaborn as sns
sns.set(style = "darkgrid")
iris=sns.load_dataset('iris')
sns.scatterplot(
x=iris['sepal_width'],
y=iris['sepal_length'],
hue=iris['species'],
style=iris['species'],
size=iris['species'],
legend=False
) |
import seaborn as sns
sns.set(style = "darkgrid")
iris=sns.load_dataset('iris')
sns.scatterplot(
x=iris['sepal_width'],
y=iris['sepal_length'],
hue=iris['species'],
style=iris['species'],
size=iris['species'],
legend=False
)

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined.
Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.
More Posts - Website
2021-01-09, 20:37
Hier ein einfaches Beispiel für einen Scatterplot mit Python und dem Seaborn Modul. Das Beispiel nutzt den bekannten Iris-Datensatz von R. Fisher, der gut für Klassifikationstechniken genutzt werden kann.
import seaborn as sns
iris=sns.load_dataset('iris')
sns.scatterplot(x=iris['sepal_width'],y=iris['sepal_length'],hue=iris['species']) |
import seaborn as sns
iris=sns.load_dataset('iris')
sns.scatterplot(x=iris['sepal_width'],y=iris['sepal_length'],hue=iris['species'])

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined.
Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.
More Posts - Website
2020-12-30, 18:16
Nachdem wir uns im letzten Artikel angeschaut hatten, wie man mit openpyxl
Funktionen Felder in CSV-Dateien mit Werten aus Excel-Dateien ersetzen kann, heute nun die pandas
Implementierung dessen.
Sie nutzt auch openpyxl
zum Einlesen der Excel-Datei, da xlrd
, das bisher von pandas genutzte Modul für Excel-Dateien, den Support für XLSX Formate eingestellt hat.
Die Arbeitsweise des Codes ist recht einfach. pandas liest die Datei, da die Tabelle nicht links oben anfängt, werden die erste Zeile und Spalte ignoriert und die Spalten passend benannt. Dann iterieren wird durch den Dataframe und ersetzen munter…
import pandas as pd
path = "python_test.xlsx"
df = pd.read_excel(path,engine='openpyxl',
sheet_name='Tabelle2',skiprows=1,
usecols={1,2},header=None)
df = df.rename(columns={1: "Key", 2: "Value"})
with open('Python_test.txt') as input_file:
text = input_file.read()
for index, row in df.iterrows():
text = text.replace(row['Key'] ,str(row['Value']))
with open('Python_test_output_pd.txt','w') as output_file:
output_file.write(text) |
import pandas as pd
path = "python_test.xlsx"
df = pd.read_excel(path,engine='openpyxl',
sheet_name='Tabelle2',skiprows=1,
usecols={1,2},header=None)
df = df.rename(columns={1: "Key", 2: "Value"})
with open('Python_test.txt') as input_file:
text = input_file.read()
for index, row in df.iterrows():
text = text.replace(row['Key'] ,str(row['Value']))
with open('Python_test_output_pd.txt','w') as output_file:
output_file.write(text)
Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined.
Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.
More Posts - Website
2020-12-26, 18:46
Nachdem wir bereits mit Excel und VBA Platzhalter in CSV Dateien gesucht und mit Inhalten ersetzt haben heute das ganze mit Python und OpenPyxl.
Ausgangspunkt ist eine Exceldatei „python_test.xlsx“ mit einer Named Range „Felder“ im Tabellenblatt „Tabelle2“.

Mit der openpyxl
Bibliothek laden wir das Excel-Blatt und holen uns die Inhalte der Range in ein Dictionary. Jeden der Keys aus dem Dictionary suchen wir dann in der CSV Datei und ersetzen ihn gegen den Wert aus der Excel-Datei.
# -*- coding: utf-8 -*-
import openpyxl
path = "python_test.xlsx"
workbook = openpyxl.load_workbook(path)
def get_sheet_and_location(workbook, named_range):
x = list(workbook.defined_names['Felder'].destinations)[0]
return x[0], x[1].replace('$','').split(':')[0],x[1].replace('$','').split(':')[1]
sheet, start, stop = get_sheet_and_location(workbook,'Felder')
worksheet = workbook[sheet]
rng=worksheet[start:stop]
replacements = {}
for row in rng:
c1, c2 = row
replacements[c1.value] = c2.value
with open('Python_test.txt') as input_file:
text = input_file.read()
for key in replacements:
text = text.replace(key,str(replacements[key]))
with open('Python_test_output.txt','w') as output_file:
output_file.write(text) |
# -*- coding: utf-8 -*-
import openpyxl
path = "python_test.xlsx"
workbook = openpyxl.load_workbook(path)
def get_sheet_and_location(workbook, named_range):
x = list(workbook.defined_names['Felder'].destinations)[0]
return x[0], x[1].replace('$','').split(':')[0],x[1].replace('$','').split(':')[1]
sheet, start, stop = get_sheet_and_location(workbook,'Felder')
worksheet = workbook[sheet]
rng=worksheet[start:stop]
replacements = {}
for row in rng:
c1, c2 = row
replacements[c1.value] = c2.value
with open('Python_test.txt') as input_file:
text = input_file.read()
for key in replacements:
text = text.replace(key,str(replacements[key]))
with open('Python_test_output.txt','w') as output_file:
output_file.write(text)
Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined.
Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.
More Posts - Website
2020-10-25, 07:43
Ausgehend von meinem ersten Artikel zu diesem Thema habe ich jetzt noch eine Erweiterung des Skripts vorgenommen. Als Spammer erkannte E-Mail-Adressen werden jetzt auch automatisch geblockt.
Dazu suche ich alle „Dauerhaft von der Liste verbannen“ Checkboxen — ihre Namen beginnen alle mit „ban-“ — und klicke sie.
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
from selenium.common.exceptions import NoSuchElementException
opts = Options()
browser = Firefox(executable_path=r"C:\geckodriver-v0.27.0\geckodriver.exe",
options=opts)
browser.implicitly_wait(3)
browser.get('<url>')
search_form = browser.find_element_by_name('adminpw')
search_form.send_keys('<password>')
search_form.submit()
try:
field = browser.find_element_by_name('discardalldefersp')
field.click()
browser.implicitly_wait(3)
submit = browser.find_element_by_name('submit')
submit.click()
except NoSuchElementException:
print('No new messages to be discarded')
browser.implicitly_wait(3)
fields = browser.find_elements_by_xpath("//input[@value='3']")
emails = browser.find_elements_by_xpath('//td[contains(text(),"@")]')
banfields = browser.find_elements_by_xpath('//input[contains(@name,"ban-")]')
if len(fields) == 0:
print('No new requests to be discarded, closing browser')
browser.close()
else:
if len(fields) == len(emails) and len(fields) == len(banfields) :
zipped_list = list(zip(emails, fields, banfields))
for i in zipped_list:
email, field, banfield = i
if not email.text.endswith(')'):
field.click()
banfield.click() |
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
from selenium.common.exceptions import NoSuchElementException
opts = Options()
browser = Firefox(executable_path=r"C:\geckodriver-v0.27.0\geckodriver.exe",
options=opts)
browser.implicitly_wait(3)
browser.get('<url>')
search_form = browser.find_element_by_name('adminpw')
search_form.send_keys('<password>')
search_form.submit()
try:
field = browser.find_element_by_name('discardalldefersp')
field.click()
browser.implicitly_wait(3)
submit = browser.find_element_by_name('submit')
submit.click()
except NoSuchElementException:
print('No new messages to be discarded')
browser.implicitly_wait(3)
fields = browser.find_elements_by_xpath("//input[@value='3']")
emails = browser.find_elements_by_xpath('//td[contains(text(),"@")]')
banfields = browser.find_elements_by_xpath('//input[contains(@name,"ban-")]')
if len(fields) == 0:
print('No new requests to be discarded, closing browser')
browser.close()
else:
if len(fields) == len(emails) and len(fields) == len(banfields) :
zipped_list = list(zip(emails, fields, banfields))
for i in zipped_list:
email, field, banfield = i
if not email.text.endswith(')'):
field.click()
banfield.click()
Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined.
Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.
More Posts - Website
2020-10-04, 18:04
Vor einigen Monaten habe ich mir günstig auf Ebay ein Siemens Nixdorf BA 63 USB Display gekauft, das VFD (vacuum fluorescent display) Technologie für die Anzeige nutzt und 2×20 Zeichen bietet.
Als passendste Python-Bibliothek nutze ich https://github.com/stephanemouton/VFD-WCN, die Anleitung zur Einrichtung wird im github sehr gut beschrieben.
Hier der Quellcode, der die Ausgabe im Bild erzeugt:
from vfdpos import *
factory=WincorNixdorfDisplayFactory()
VFDs = factory.get_vfd_pos()
MyVFD = VFDs[0]
MyVFD.clearscreen()
MyVFD.poscur(1, 1)
MyVFD.write_msg("Hallo")
MyVFD.write_msg("Welt")
MyVFD.write_msg("1234567abcd\r")
MyVFD.poscur(2, 1)
MyVFD.write_msg("ABCDEFüäößi")
MyVFD.close()

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined.
Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.
More Posts - Website
2020-09-27, 14:27
Im ersten Artikel zu diesem Thema hatte ich schon beschrieben, wie man mit Pi-Hole DNS Lookups so unterbinden kann, dass man Fortnite oder andere Zeitfresser temporär blockieren kann. In diesem Teil erweitern wir das Skript um eine Statusabfrage. Dazu fügen wir einfach eine Route hinzu, die die URL mit dem Parameter /status
abfragt. Dann wird der Inhalt der epicstatus.txt
abgefragt, die von den Routen /on
und /off
mit dem Zeitstempel versehen wurde.
import os
from datetime import datetime
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return('<h1>Use /off and /on to enable/disable blocking, /status to get epic.log</h1>')
@app.route('/<param>')
def setter(param):
if param=='status':
with open('/home/pi/epicstatus.txt') as f:
content = f.read()
return '<h2>' + content + '</h2>'
if param=='off':
os.system("/usr/local/bin/pihole regex '.*\.epicgames.com' > /home/pi/epic.log")
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open('/home/pi/epicstatus.txt','w') as ausgabe:
ausgabe.write(now + ' off')
return '<h1>Turning off Fortnite</h1>'
elif param=='on':
os.system("/usr/local/bin/pihole regex -d '.*\.epicgames.com' > /home/pi/epic.log")
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open('/home/pi/epicstatus.txt','w') as ausgabe:
ausgabe.write(now+ ' on')
return '<h1>Turning on Fortnite</h1>' |
import os
from datetime import datetime
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return('<h1>Use /off and /on to enable/disable blocking, /status to get epic.log</h1>')
@app.route('/<param>')
def setter(param):
if param=='status':
with open('/home/pi/epicstatus.txt') as f:
content = f.read()
return '<h2>' + content + '</h2>'
if param=='off':
os.system("/usr/local/bin/pihole regex '.*\.epicgames.com' > /home/pi/epic.log")
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open('/home/pi/epicstatus.txt','w') as ausgabe:
ausgabe.write(now + ' off')
return '<h1>Turning off Fortnite</h1>'
elif param=='on':
os.system("/usr/local/bin/pihole regex -d '.*\.epicgames.com' > /home/pi/epic.log")
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open('/home/pi/epicstatus.txt','w') as ausgabe:
ausgabe.write(now+ ' on')
return '<h1>Turning on Fortnite</h1>'
Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined.
Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.
More Posts - Website
2020-09-26, 19:53
Hier ein kurzes Beispiel, wie man mit Python-Modulen Dateien kopieren, zippen und löschen kann.
import zipfile
from shutil import copyfile
from os import unlink
# copy file
copyfile('dtk-authoryear.bbx' , './dtk-bibliography/dtk-authoryear.bbx')
copyfile('dtk-authoryear.dbx' , './dtk-bibliography/dtk-authoryear.dbx')
copyfile('dtk-bibliography.pdf', './dtk-bibliography/dtk-bibliography.pdf')
copyfile('dtk-bibliography.tex', './dtk-bibliography/dtk-bibliography.tex')
# create the zip file
with zipfile.ZipFile('dtk-bibliography.zip', 'w', zipfile.ZIP_DEFLATED) as z:
z.write('./dtk-bibliography/README.md')
z.write('./dtk-bibliography/dtk-authoryear.bbx')
z.write('./dtk-bibliography/dtk-authoryear.dbx')
z.write('./dtk-bibliography/dtk-bibliography.pdf')
z.write('./dtk-bibliography/dtk-bibliography.tex')
# delete copied files
unlink('./dtk-bibliography/dtk-authoryear.bbx')
unlink('./dtk-bibliography/dtk-authoryear.dbx')
unlink('./dtk-bibliography/dtk-bibliography.pdf')
unlink('./dtk-bibliography/dtk-bibliography.tex') |
import zipfile
from shutil import copyfile
from os import unlink
# copy file
copyfile('dtk-authoryear.bbx' , './dtk-bibliography/dtk-authoryear.bbx')
copyfile('dtk-authoryear.dbx' , './dtk-bibliography/dtk-authoryear.dbx')
copyfile('dtk-bibliography.pdf', './dtk-bibliography/dtk-bibliography.pdf')
copyfile('dtk-bibliography.tex', './dtk-bibliography/dtk-bibliography.tex')
# create the zip file
with zipfile.ZipFile('dtk-bibliography.zip', 'w', zipfile.ZIP_DEFLATED) as z:
z.write('./dtk-bibliography/README.md')
z.write('./dtk-bibliography/dtk-authoryear.bbx')
z.write('./dtk-bibliography/dtk-authoryear.dbx')
z.write('./dtk-bibliography/dtk-bibliography.pdf')
z.write('./dtk-bibliography/dtk-bibliography.tex')
# delete copied files
unlink('./dtk-bibliography/dtk-authoryear.bbx')
unlink('./dtk-bibliography/dtk-authoryear.dbx')
unlink('./dtk-bibliography/dtk-bibliography.pdf')
unlink('./dtk-bibliography/dtk-bibliography.tex')
Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined.
Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.
More Posts - Website