df_demo['userid'].value_counts()
df_demo.rename(columns={"update_time_x":"update_time","department_x":"department"}, inplace=True)
df_demo.drop(["update_time","department,"],axis=1)
df = df.sort_values(by=["end_time", "userid"])
- pandas to_sql方法写入myql时的内部事务操作:
from sqlalchemy import create_engine
def run(self):
engine = create_engine('mysql+pymysql://user:password@host:port/database',encoding='utf8')
with engine.connect() as conn:
trans = conn.begin()
try:
conn.execute("""delete from table1 where end_time ='2099-12-31'""")
my_df.to_sql(name="mytable", con=conn, index=False,if_exists="append")
except Exception as e:
trans.rollback()
raise e
else:
trans.commit()
trans.close()
return "ok"
changed_un.empty == True #True 表示为空,False表示不为空
- 将dataframe 通过某一列或几列进行分组,生成多个dataframe,将每个datafame导出到一个excel工作簿中
gropuyby_df = pd.read_excel("aa.xlsx").groupby(['邮箱','所属销售'])
for i in gropuyby_df:
i[1].to_excel("./FileDir/{}.xlsx".format(i[0][1]),index=False)
df_today['department'] = df_today['department'].str.replace(' ', '')
df_today.dtypes
df_today['update_time'].dtypes
df_today['update_time'].to_list()
- dataframe 根据某一列分组,获取另外一列的最大值
df = df.groupby('group_md5_id').apply(lambda t: t[t.chat_time == t.chat_time.max()])
- dataframe 中某一列中数值类型为字符串且将其进行格式化输出
df_today['update_time'] = df_today['update_time'].apply(lambda x: x.strftime("%Y-%m-%d"))
- dataframe 将某一列时间类型的元素转化为时间戳类型
def convert(x):
d = datetime.datetime.strptime(x,"%Y-%m-%d %H:%M:%S")
t = d.timetuple()
timeStamp = int(time.mktime(t))
return timeStamp
df['ts_start_time'] = df.start_time.apply(lambda x: convert(x))
df['start_time'] = pd.to_datetime(df['start_time'])
df2['累加数'] = df2['周期'].cumsum()
- dataframe 导出一个excel工作簿的多个sheet
writer = pd.ExcelWriter('demo.xlsx',index=False)
df1.to_excel(writer, sheet_name="sheet1", index=False)
df2.to_excel(writer, sheet_name="sheet2", index=False)
df[df['age']>=12] # 获取年龄大于等于12岁的行
df[~df['age']>=12] # 获取年龄小于等于12岁的行
df = df[df['age'].isnull() == False] #删除年龄为缺少值的行数据
df_total["is_today_add_wechat"] = df_total[["is_power_today_leads", "is_mon_add_wechat"]].apply(lambda x: 1 if x["is_power_today_leads"]==1 and x["is_mon_add_wechat"] else 0, axis=1)
df.groupby(by=['学科名称','班主任id','班主任名称','上课时段']).agg(班级数=('班级id','count'),学员数=('学员量','sum'),班级id列表=("班级id", lambda x : ",".join(x.unique())),).reset_index()
df['变更后上课时段']=df['变更后上课时段'].fillna(df['上课时段'])