1)pandas及其他:
1.1)replace:
pdsub540.replace(to_replace=1, value=0.005, inplace=True) # inplace改变原值,regex正则式匹配
源dataframe.replace(需要查找的值=1,改变成的值=0.005,对源表进行更改),如果需要正则式匹配,则, regex=True,示例:
pdsub540.replace(to_replace='^0.0*0$', value=0.005, regex=True , inplace=True) # inplace改变原值,regex正则式匹配
1.2)dropna:
n1 = pdsub8['1n'].dropna(how="all")
删除dataframe中全部缺失值。
1.3)推导式:
[12.206 if x == int(1) else x for x in ttest]
等同于:
for x in ttest:
if x == int(1):
x = 12.206
else:
x
1.4)格式化输出:
"{:.1f}".format(uk1)
保留小数点后1位。
1.5)concat:
df1 = pd.concat([pd.DataFrame({'xx': hard}),
pd.DataFrame({'xxxxxxxxx': listurel100})],axis=1)
concat连接dataframe, axis=1按列连接,axis=0为按行列连接,无需行列数一致。
2)openpyxl及其他:
2.1)读取并保存到新的sheet中:
book = openpyxl.load_workbook(listA[i])
writer = pd.ExcelWriter(listA[i], engine='openpyxl')
writer.book = book
df1.to_excel(writer, sheet_name='xxxx', index=0)
df2.to_excel(writer, sheet_name='xxxxxxxx', index=0)
worksheet = book['不确定度']
worksheet.column_dimensions['A'].width = 25
第四行和第五行末尾出现的index=0为不将index写入excel表格中;
第七行为将A的列宽设为25
2.2)页眉:
ws.oddHeader.left.text = "xxxx"
为Excel设置页眉:oddHeader,设置页脚:oddFooter
2.3)页眉字号:
ws.oddHeader.left.size = 10
页眉字体大小
2.4)页眉字体:
ws.oddHeader.left.font = "思源宋体CN"
2.5)Excel行高:
for d in range(5000):
ws.row_dimensions[d].height = 20
设置5000行行高为20
2.6)设置列宽:
for d in ['A', 'B', 'C', 'D', 'E']:
ws.column_dimensions[d].width = 16
当然也可以使用索引设置,批量更方便
2.7)设置字体:
font = Font(
name="思源宋体CN", # 字体
size=20, # 字号
bold=True) # 加粗,True/False
先设置一个模板,之后:
ws['A1'].font = font
2.8)对齐:
plus = Alignment(
horizontal='center', # 水平对齐,left左、center居中、right右
vertical='center' # 垂直对齐, top、center居中、bottom
wrap_text=False) # 自动换行
先设置一个模板,之后:
ws['A1'].alignment = plus
2.9)框线:
roundset = Border(left=Side(style='thin', color=colors.BLACK), # 左边框
right=Side(style='thin', color=colors.BLACK), # 右边框
top=Side(style='thin', color=colors.BLACK), # 上边框
bottom=Side(style='thin', color=colors.BLACK)) # 下边框
2.10)合并单元格:
ws.merge_cells(range_string='A1:E1') # 合并单元格
2.11)每5列写一次值:
for l in range(len(hard0)):
if l <= 4:
ws.cell(27, l + 1, hard0[l]).font = font3
ws.cell(28, l + 1,listUk0[l]).font = font3
2.12)删除空行:
for x in range(34, 26, -1):
sc = ws.cell(x, 1).value
if sc is None:
ws.delete_rows(x)
s3.append(sc)
else:
pass
删除空行后可能会改变之前设置好的格式,因此:
up3 = 125 - len(s1) - len(s2) - len(s3) + 1
up31 = 125 - len(s1) - len(s2) - len(s3) + 2
ws.row_dimensions[up3].height = 80
ws.row_dimensions[up31].height = 50
up32 = ['A' + str(up3) + ':' + 'E' + str(up3)]
up33 = ['A' + str(up31) + ':' + 'B' + str(up31)]
up34 = ['C' + str(up31) + ':' + 'D' + str(up31)]
根据删除的空行数重新设置一下格式