1)pandas及其他:

1.1)replace:

  1. pdsub540.replace(to_replace=1, value=0.005, inplace=True) # inplace改变原值,regex正则式匹配

源dataframe.replace(需要查找的值=1,改变成的值=0.005,对源表进行更改),如果需要正则式匹配,则, regex=True,示例:

  1. pdsub540.replace(to_replace='^0.0*0$', value=0.005, regex=True , inplace=True) # inplace改变原值,regex正则式匹配

1.2)dropna:

  1. n1 = pdsub8['1n'].dropna(how="all")

删除dataframe中全部缺失值。

1.3)推导式:

  1. [12.206 if x == int(1) else x for x in ttest]

等同于:

  1. for x in ttest:
  2. if x == int(1):
  3. x = 12.206
  4. else:
  5. x

1.4)格式化输出:

  1. "{:.1f}".format(uk1)

保留小数点后1位。

1.5)concat:

  1. df1 = pd.concat([pd.DataFrame({'xx': hard}),
  2. pd.DataFrame({'xxxxxxxxx': listurel100})],axis=1)

concat连接dataframe, axis=1按列连接,axis=0为按行列连接,无需行列数一致。

2)openpyxl及其他:

2.1)读取并保存到新的sheet中:

  1. book = openpyxl.load_workbook(listA[i])
  2. writer = pd.ExcelWriter(listA[i], engine='openpyxl')
  3. writer.book = book
  4. df1.to_excel(writer, sheet_name='xxxx', index=0)
  5. df2.to_excel(writer, sheet_name='xxxxxxxx', index=0)
  6. worksheet = book['不确定度']
  7. worksheet.column_dimensions['A'].width = 25

第四行和第五行末尾出现的index=0为不将index写入excel表格中;
第七行为将A的列宽设为25

2.2)页眉:

  1. ws.oddHeader.left.text = "xxxx"

为Excel设置页眉:oddHeader,设置页脚:oddFooter

2.3)页眉字号:

  1. ws.oddHeader.left.size = 10

页眉字体大小

2.4)页眉字体:

  1. ws.oddHeader.left.font = "思源宋体CN"

2.5)Excel行高:

  1. for d in range(5000):
  2. ws.row_dimensions[d].height = 20

设置5000行行高为20

2.6)设置列宽:

  1. for d in ['A', 'B', 'C', 'D', 'E']:
  2. ws.column_dimensions[d].width = 16

当然也可以使用索引设置,批量更方便

2.7)设置字体:

  1. font = Font(
  2. name="思源宋体CN", # 字体
  3. size=20, # 字号
  4. bold=True # 加粗,True/False

先设置一个模板,之后:

  1. ws['A1'].font = font

2.8)对齐:

  1. plus = Alignment(
  2. horizontal='center', # 水平对齐,left左、center居中、right右
  3. vertical='center' # 垂直对齐, top、center居中、bottom
  4. wrap_text=False) # 自动换行

先设置一个模板,之后:

  1. ws['A1'].alignment = plus

2.9)框线:

  1. roundset = Border(left=Side(style='thin', color=colors.BLACK), # 左边框
  2. right=Side(style='thin', color=colors.BLACK), # 右边框
  3. top=Side(style='thin', color=colors.BLACK), # 上边框
  4. bottom=Side(style='thin', color=colors.BLACK)) # 下边框

2.10)合并单元格:

  1. ws.merge_cells(range_string='A1:E1') # 合并单元格

2.11)每5列写一次值:

  1. for l in range(len(hard0)):
  2. if l <= 4:
  3. ws.cell(27, l + 1, hard0[l]).font = font3
  4. ws.cell(28, l + 1,listUk0[l]).font = font3

2.12)删除空行:

  1. for x in range(34, 26, -1):
  2. sc = ws.cell(x, 1).value
  3. if sc is None:
  4. ws.delete_rows(x)
  5. s3.append(sc)
  6. else:
  7. pass

删除空行后可能会改变之前设置好的格式,因此:

  1. up3 = 125 - len(s1) - len(s2) - len(s3) + 1
  2. up31 = 125 - len(s1) - len(s2) - len(s3) + 2
  3. ws.row_dimensions[up3].height = 80
  4. ws.row_dimensions[up31].height = 50
  5. up32 = ['A' + str(up3) + ':' + 'E' + str(up3)]
  6. up33 = ['A' + str(up31) + ':' + 'B' + str(up31)]
  7. up34 = ['C' + str(up31) + ':' + 'D' + str(up31)]

根据删除的空行数重新设置一下格式