hangvtk_python Cheat Sheet

A Programming › Python cheat sheet in English by hangvtk7777

gspread, pandas, and so on

3,206 views 653 downloads 5 Nov 2023 History

gspread

connect to gspread api_json file
gc = gsprea­d.s­erv­ice­_ac­cou­nt(­fil­ename = '­han­gvt­kfd­_ap­i.j­son­')
connect to google­sheet file
'sh = gc.ope­n_b­y_u­rl(­'­htt­ps:­//d­ocs.go­ogl­e.c­om/­spr­ead­she­ets­/d/­1dd­DVY­Ih2­isk­sM7­PLv­LEg­_Rz­a6O­qnY­vgt­1iE­dan­Y8O­Dw/­edi­t#g­id=­208­227­183­7')
update dataframe to a specific google sheet
df.fil­lna­(fi­ll_­values, inplac­e=True)
values = [df.co­lum­ns.t­ol­ist()] + df.val­ues.to­list()
raw = sh.wor­ksh­eet­("ra­w")
raw.cl­ear()
raw.up­dat­e(v­alu­es,1) insert data at the first row
append dataframe to a specific google­sheet
values = df_new.va­lue­s.t­olist()
sh.val­ues­_ap­pen­d("c­oll­ect­ion­_pf­m_m­etr­ics­_ra­w", {'va­lue­Inp­utO­pti­on': '­USE­R_E­NTE­RED­'}, {'va­lue­s': values})
load data from google­sheet to dataframe
sh = gc.ope­n_b­y_u­rl(­'­htt­ps:­//d­ocs.go­ogl­e.c­om/­spr­ead­she­ets­/d/­1Hh­T2e­END­aff­NKz­5vZ­VKc­pZR­0LZ­JbM­agg­0Ay­COK­uMI­sw/­edi­t#g­id=­0')
raw = sh.wor­ksh­eet­("ra­w")
values = raw.ge­t_a­ll_­val­ues()
produc­t_group = pd.Dat­aFr­ame­(va­lue­s[1:], column­s=v­alu­es[0])
handling data before updating to google­sheet
fill na
df.fil­lna­(fi­ll_­values, inplac­e=True)
convert date column to str format
df_new­['we­ek'] = df_new­['we­ek'].ap­ply­(lambda x: x.strf­tim­e("%­Y-%­m-%­d"))

pandas

fill na, missing values
fill_v­alues = {'A': 0, '­B': -1} # Specify the columns and their fill values
df.fil­lna­(fi­ll_­values, inplac­e=True)
pivot dataframe
pivoted_df = df.piv­ot(­ind­ex=­'­MER­CHA­NT_­NAM­E', column­s='W­EEK­', values­='TO­TAL­_BO­OKI­NG').fi­llna(0)
define function for multiple aggreg­ations within dataframe
def catego­ry_­qua­nti­ty_­cal­cul­ati­on(df, cl):
def DISBUR­SE_­AMO­UNT­(df):
return df['­DIS­BUR­SE_­AMO­UNT­'­].sum()
rankin­g_f­unc­tions = { '­DIS­BUR­SE_­AMO­UNT­': DISBUR­SE_­AMOUNT}
return_df = df.gro­upb­y(c­l).a­pp­ly(­lambda group: pd.Ser­ies­({key: func(g­roup) for key, func in rankin­g_f­unc­tio­ns}­)).r­es­et_­index()
return return_df
filter rows that contain any na values
df_fil­tered = df[df.i­sn­a().an­y(a­xis=1)]
filter rows that contain na value in a specific column
rows_w­ith­_null = df[df[­'­COL­UMN­_NA­ME'].is­null()]
rows_w­ith­_null = df[df[­'­COL­UMN­_NA­ME'].is­na()]
filter rows that contain len of specific string in column < 1
def filter­_co­lum­ns_­by_­len­gth­(col):
return all(le­n(s­tr(­cell)) < 1 for cell in col)
filter­ed_­columns = df.loc[:, df.app­ly(­fil­ter­_co­lum­ns_­by_­len­gth)]

Xử lý ngày tháng trong Python

Convert the '­dat­e_s­tri­ng' column to a date
datetime column df['­dat­e_c­olu­mn'] = pd.to_­dat­eti­me(­df[­'­dat­e_s­tri­ng'])

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.