51 - 100 Flashcards
numpy.flatten(order=’C’)
Return a copy of the array collapsed into one dimension.
a = np.array([[1,2], [3,4]]) a.flatten() 👉 array([1, 2, 3, 4])
a = np.array([[1,2], [3,4]]) a.flatten('F') 👉 array([1, 3, 2, 4])
my_array = numpy.array([[1,2,3], [4,5,6]]) print my_array.flatten() 👉 [1 2 3 4 5 6]
SQL.datetime
function to manipulate datetime values. The function accepts a time string and one or more modifiers.
SELECT datetime('now','-1 day','localtime');
SELECT datetime('now','localtime')
CREATE TABLE referrals( id INTEGER PRIMARY KEY, source TEXT NOT NULL, created_at TEXT DEFAULT CURRENT_TIMESTAMP );
math.exp()
the method returns E raised to the power of x (Ex).
print(math.exp(65)) 👉 1.6948892444103338e+28
print(math.exp(-6.89)) 👉 0.0010179138409954387
pandas.read_sql(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None)
Read SQL query or database table into a DataFrame.
from sqlite3 import connect conn = connect(':memory:') df = pd.DataFrame(data=[[0, '10/11/12'], [1, '12/11/10']], columns=['int_column', 'date_column']) df.to_sql('test_data', conn)
pd.read_sql('SELECT int_column, date_column FROM test_data', conn) int_column date_column 0 0 10/11/12 1 1 12/11/10
pandas.read_gbq(query, project_id=None, index_col=None, col_order=None, reauth=False, auth_local_webserver=False, dialect=None, location=None, configuration=None, credentials=None, use_bqstorage_api=None, max_results=None, progress_bar_type=None)
Load data from Google BigQuery. This function requires the pandas-gbq package.
pandas.DataFrame.to_sql(name, con, schema=None, if_exists=’fail’, index=True, index_label=None, chunksize=None, dtype=None, method=None)
Write records stored in a DataFrame to a SQL database.
from sqlalchemy import create_engine engine = create_engine('sqlite://', echo=False) df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']}) df.to_sql('users', con=engine) engine.execute("SELECT * FROM users").fetchall() [(0, 'User 1'), (1, 'User 2'), (2, 'User 3')]
df2 = pd.DataFrame({'name' : ['User 6', 'User 7']}) df2.to_sql('users', con=engine, if_exists='append') engine.execute("SELECT * FROM users").fetchall()
pandas.read_sql_query(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, chunksize=None, dtype=None)
Read SQL query into a DataFrame. Returns a DataFrame corresponding to the result set of the query string.
pandas.DataFrame.filter(items=None, like=None, regex=None, axis=None)
Subset the dataframe rows or columns according to the specified index labels. The filter is applied to the labels of the index.
df = pd.DataFrame(np.array(([1, 2, 3], [4, 5, 6])), index=['mouse', 'rabbit'], columns=['one', 'two', 'three']) df.filter(items=['one', 'three']) one three mouse 1 3 rabbit 4 6
pandas.DataFrame.join(other, on=None, how=’left’, lsuffix=’’, rsuffix=’’, sort=False)
Join columns with other DataFrame either on an index or on a key column. Efficiently join multiple DataFrame objects by index at once by passing a list.
df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'], 'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']}) other = pd.DataFrame({'key': ['K0', 'K1', 'K2'], 'B': ['B0', 'B1', 'B2']}) df.join(other, lsuffix='_caller', rsuffix='_other')
pandas.DataFrame.unstack(level=- 1, fill_value=None)
Pivot a level of the (necessarily hierarchical) index labels. Returns a DataFrame having a new level of column labels whose inner-most level consists of the pivoted index labels.
index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'), ('two', 'a'), ('two', 'b')]) s = pd.Series(np.arange(1.0, 5.0), index=index) s.unstack(level=-1) a b one 1.0 2.0 two 3.0 4.0
s.unstack(level=0) one two a 1.0 3.0 b 2.0 4.0
matplotlib.xlim() and matplotlib.ylim()
Get or set the x or y limits of the current axes.
left, right = xlim() # return the current xlim xlim((left, right)) # set the xlim to left, right xlim(left, right) # set the xlim to left, right
xlim(right=3) # adjust the right leaving left unchanged xlim(left=1) # adjust the left leaving right unchanged
matplotlib.gca(**kwargs)
If there are currently no Axes on this Figure, a new one is created using Figure.add_subplot.
plt.close('all') arr = np.arange(100).reshape((10, 10)) fig = plt.figure(figsize =(4, 4)) im = plt.imshow(arr, interpolation ="none", cmap ="plasma") divider = make_axes_locatable(plt.gca()) cax = divider.append_axes("left", "15 %", pad ="30 %") plt.colorbar(im, cax = cax) fig.suptitle('matplotlib.pyplot.gca() function\ Example\n\n', fontweight ="bold") plt.show()
matplotlib.set_position()
function in the axes module of matplotlib library is used to set the axes position.
matplotlib.suptitle(t, **kwargs)
Add a centered suptitle to the figure.
d = {'series a' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']), 'series b' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d) title_string = "This is the title" subtitle_string = "This is the subtitle" plt. figure() df. plot(kind='bar') plt. suptitle(title_string, y=1.05, fontsize=18) plt. title(subtitle_string, fontsize=10)
matplotlib.gcf()
Get the current figure. If there is currently no figure on the pyplot figure stack, a new one is created using figure().
plot.plot([2, 3, 4]) figure = plot.gcf().canvas ag = figure.switch_backends(FigureCanvasAgg) ag.draw() A = np.asarray(ag.buffer_rgba()) from PIL import Image img = Image.fromarray(A) img.show()
seaborn.set(*args, **kwargs)
Alias for set_theme(), which is the preferred interface. This function may be removed in the future.
numpy.ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)
An array object represents a multidimensional, homogeneous array of fixed-size items.
np.ndarray(shape=(2,2), dtype=float, order='F') 👉 array([[0.0e+000, 0.0e+000], [ nan, 2.5e-323]])
np.ndarray((2,), buffer=np.array([1,2,3]), offset=np.int_().itemsize, dtype=int) 👉 array([2, 3])
numpy.pi
numpy.pi
numpy.add(x1, x2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj])
Add arguments element-wise.
np. add(1.0, 4.0) 👉 5. 0
x1 = np.arange(9.0).reshape((3, 3)) x2 = np.arange(3.0) np.add(x1, x2) 👉 array([[ 0., 2., 4.], [ 3., 5., 7.], [ 6., 8., 10.]])
x1 = np.arange(9.0).reshape((3, 3)) x2 = np.arange(3.0) x1 + x2 👉 array([[ 0., 2., 4.], [ 3., 5., 7.], [ 6., 8., 10.]])
numpy.matmul(x1, x2, /, out=None, *, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj, axes, axis])
Matrix product of two arrays.
a = np.ones([9, 5, 7, 4]) c = np.ones([9, 5, 4, 3]) np.dot(a, c).shape 👉 (9, 5, 7, 9, 5, 3) np.matmul(a, c).shape 👉 (9, 5, 7, 3)
a = np.array([[1, 0], [0, 1]]) b = np.array([[4, 1], [2, 2]]) np.matmul(a, b) 👉 array([[4, 1], [2, 2]])