Leetcode-30 Days of Pandas整理(1/2)

J
J NOTE

Hello,這篇整理了我在進行Leetcode-30 Days of Pandas所遇到的各種問題與解答,同時也彙整了一些基礎語法,各種用法都會有對應的題目,如果有更好的方式也歡迎一起討論!

(本篇文章以markdown撰寫,參考文件為https://markdown.tw/)

八月完成Leetcode的免費挑戰以後一直沒時間整理筆記

這幾天一鼓作氣把不熟跟常常搞混的一次放上來
主要都是pandas中會用到的語法,merge,melt,groupby這些


A

abcd
0valuevaluevaluevalue
1valuevaluevaluevalue
2valuevaluevaluevalue
df=A[(A['a']>=100|A['b']>=200)]
#table A中篩選特定數值
#相關用法: | ->or, & -> and
df=A[['a']].rename(columns={'a':'a1'})
#rename column name
df=A[A['a']=A['b']]
#a的內容=b 
df1=df.drop_duplicates().sort_values(by='a')
df=A[A['b'].str.len()>15]
#篩選b中字串長度>15的欄位
A['c']=A[~A['b'].str.startswith('AB')]
#將b欄位中開頭不為AB的欄位額外新增,並命名為c
str.capitalize()
#首字大寫
str.match(r'^[a-zA-Z][a-zA-Z\d_.-]@leetcode\.com')]
#@leetcode.com結尾
#首字為字母
#帳號包含-._
str.contains(r'^(^DIAB1)|( DIAB1)')
#包含 DIAB1的字串(DIAB100,ALNE DIAB100…)

A

idnamesalaryd_id
0
1
2

B

idname
0valuevalue
1valuevalue
2valuevalue
df1=A.merge(B,left_on='d_id',right_on='id',\
suffix=('_A','_B'))
salarymax=df1.groupby('d_id',group_keys=False).\
apply(lambda x:x[x['salary']==x['salary'].max()])
id_Aname_Asalary_Ad_idname_B
1
2
3

A

idshop1shop2shop3
01pricepriceprice
12pricepriceprice
23pricepriceprice
df=pd.Dataframe[A.melt(id_vars=['id'],var_name=['shop']\
,value_name=['price']).dropna()
idshopprice
01shop1price
12shop2price
21shop2price

A

idevent_dayinout
12020-01-23423
A['total_time']=A['out']-['in']
#add new column,value=outtime-intime
final=A.groupby(['id','event_day'])\
['total_time'].sum().reset_index()
#同個id在同一天的時間加總後,重設index
event_dayidtotal_time
2020-01-23119

A

dateproduct
2020-01-23a
2020-01-23b
2020-01-23c
df=A.grouptby('date')['product'].agg(['unique',lanbda x: ','.join(sorted(set(x)))].reset_index()
df.columns=['date','nums_sold','products']
df['products']=df['products'].str.replcace(r'(^|)Mask(,|$)',r'\1Mask\2')
result=df.sort_values(by='date')
datenums_soldproduct
2020-01-23numbera,b,c

第一次用Markdown語法編輯文章
需要一點時間適應一下!

Comments