Python programming, with examples in hydraulic engineering and in hydrology.
Sunday, November 26, 2017
Pandas sum column values according to another columns value
One-liner code to sum Pandas second columns according to same values in the first column.
df2 = df1.groupby(df1.columns[0])[df1.columns[1]].sum().reset_index()
For example, applying to a table listing pipe diameters and lenghts, the command will return total lenghts according to each unique diameters.
This functionality is similar to excel's pivot table sum.
Wednesday, November 22, 2017
Matplotlib template for Precipitation and Flow over time - Hidrograms and Hyetographs
This code works in python3, to plot a hyetograph - precipitation event (sP), together with a hydrograph (sQ), both in the same time series (t).
#-*-coding:utf-8-*-; import matplotlib.pyplot as plt from matplotlib import gridspec import numpy as np def plotHH(t,sP,sQ): fig = plt.figure() gs = gridspec.GridSpec(2, 1, height_ratios=[1, 2]) # HYDROGRAM CHART ax = plt.subplot(gs[1]) ax.plot(t,sQ) ax.set_ylabel(u'Q(m³/s)', color='b') ax.set_xlabel('Time (min.)') ax.tick_params(axis='y', colors='b') ax.xaxis.grid(b=True, which='major', color='.7', linestyle='-') ax.yaxis.grid(b=True, which='major', color='.7', linestyle='-') ax.set_xlim(min(t), max(t)) ax.set_ylim(0, max(sQ)*1.2) # PRECIPITATION/HYETOGRAPH CHART ax2 = plt.subplot(gs[0]) ax2.bar(t, sP, 1, color='#b0c4de') ax2.xaxis.grid(b=True, which='major', color='.7', linestyle='-') ax2.yaxis.grid(b=True, which='major', color='0.7', linestyle='-') ax2.set_ylabel('P(mm)') ax2.set_xlim(min(t), max(t)) plt.setp(ax2.get_xticklabels(), visible=False) plt.tight_layout() ax2.invert_yaxis() plt.gcf().subplots_adjust(bottom=0.15) plt.show() #plt.savefig(filename,format='pdf') plt.close(fig)
Labels:
bar,
Chart,
flow,
hydrograph,
hyetograph,
Line,
matplotlib,
plt,
precipitation,
python3
Subscribe to:
Posts (Atom)