python代码命令大全 python代码大全和用法

python代码大全和用法,python,代码命令大全 。小编来告诉你更多相关信息 。
一些常用的python代码合集,方便检索引用
模块1:读写excel文件from datetime import datetime

python代码命令大全 python代码大全和用法

文章插图
python代码命令大全 python代码大全和用法

文章插图
import odps
import xlwt
import os
from odps import DataFrame
import pandas as pd
import xlrd
import numpy as np
from collections import defaultdict
from collections import Counter
def write_imf(fl_save_path, data):
sh = wb.add_sheet(u\’data\’, cell_overwrite_ok=True)
colnames = data.columns.values
for i in range(0, data.shape[1]):
sh.write(0, i, colnames[i])
for i in range(1, len(data) + 1):
for j in range(0, data.shape[1]):
value = https://www.0579wy.com/article/data.iloc[i – 1, j]
try:
value.dtype
if value.dtype == \’int64\’:
value = https://www.0579wy.com/article/int(value)
if value.dtype == \’float64\’:
value = https://www.0579wy.com/article/float(value)
except(RuntimeError, TypeError, NameError, ValueError, AttributeError):
pass
sh.write(i, j, value)
wb.save(fl_save_path)
print(\’congratulation save successful!\’)
def save_pd_to_csv(fl_save_path, data):
return True
except:
return False
def get_excel_content(file_path):
wb = xlrd.open_workbook(file_path, encoding_override=\’utf-8\’)
wb_cont_imf = []
df = pd.DataFrame(wb_cont_imf[1:], columns=wb_cont_imf[0])
return df
模块2:获取各种时间def getMonthFirstDayAndLastDay(year=None, month=None):
:param year: 年份,默认是本年,可传int或str类型
:param month: 月份,默认是本月,可传int或str类型
:return: firstDay: 当月的第一天,datetime.date类型
lastDay: 当月的最后一天,datetime.date类型
if year:
year = int(year)
else:
year = datetime.date.today().year
if month:
month = int(month)
else:
month = datetime.date.today().month
firstDayWeekDay, monthRange = calendar.monthrange(year, month)
firstDay = datetime.date(year=year, month=month, day=1)
lastDay = datetime.date(year=year, month=month, day=monthRange)
return lastDay
模块3:pd中的dataframe转pngdef render_mpl_table(data, col_width=5.0, row_height=0.625, font_size=1,
bbox=[0, 0, 1, 1], header_columns=0,
ax=None,**kwargs):
if ax is None:
plt.style.use(\’ggplot\’)
ax.axis(\’off\’)
mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)
mpl_table.auto_set_font_size(False)
mpl_table.set_fontsize(font_size)
for k, cell in six.iteritems(mpl_table._cells):
cell.set_edgecolor(edge_color)
nrow = k[0]
ncol = k[1]
if nrow == 0 or ncol < header_columns:
cell.set_text_props(weight=\’bold\’, color=\’w\’)
cell.set_facecolor(header_color)
else:
cell.set_facecolor(row_colors[k[0] % len(row_colors)])
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)
plt.margins(0, 0)
return ax
模块4:绘制词云_author_ = \’xisuo\’
import datetime
import calendar
import xlwt
import os
import pandas as pd
import xlrd
import openpyxl
import numpy as np
from collections import defaultdict
import platform
from wordcloud import WordCloud,STOPWORDS
import matplotlib.pyplot as plt
from PIL import Image
def create_wordcloud(docs=None,imgs=None,filename=None):
:param docs:读入词汇txt,尽量不重复
:param imgs: 读入想要生成的图形,网上随便找
:param filename: 保存图片文件名
:return:
text = open(os.path.join(current_file, docs)).read()
alice_mask = np.array(Image.open(os.path.join(current_file, imgs)))
print(font_path)
wc = WordCloud(background_color=\”white\”,
max_words=2000,
mask=alice_mask,
stopwords=STOPWORDS.add(\”said\”)
)
wc.generate(text)
if filename is None:filename=\”词云结果.png\”
wc.to_file(os.path.join(current_file, filename))
def main():
create_wordcloud(docs=docs,imgs=imgs,filename=filename)
print(\’create wordcloud successful\’)
if __name__ == \’__main__\’:
start_time = datetime.datetime.now()
print(\’start running program at:%s\’ % start_time)

推荐阅读