记录Python中遇到的问题,方便之后查询,假如这种方式比Google快捷,便是赚到了
Most pythonic way to delete a file which may not exist
1234try:os.remove(filename)except OSError:pass
format a floating number 尤其是不要出现可恶的科学计数法(编程中很难找到一种场景需要科学记数法)
"{:10.4f}".format(x)
or'% 6.2f' % v
处理日期
12time_test = dt.strptime(str_test, '%Y-%m-%d')str_out = dt.strftime(time_test, '%Y-%m-%d')
计算日期之间的差
123(last_date - first_date).days(last_date - first_date).seconds可以根据这两项算小时的差
- pandas
- Converting strings to floats 12df.a = df.a.astype(float).fillna(0.0) ordf.a = pd.to_numeric(df.a, errors='ignore')
- Converting strings to floats
- convert some columns into rows1df2 = pd.melt(df, id_vars=["location", "name"], var_name="Date", value_name="Value")
- set_index
apply 是非常重要的神器,例如这个例子
12345df['channel'] = df['wise_channel'].apply(lambda x:x.split("*")[0])```5. [most pythonic way to pad a numeric string with zeroes to the left](http://stackoverflow.com/questions/339007/nicest-way-to-pad-zeroes-to-string)for stringsi.zfill(3)
1for numbers‘{0:03d}’.format(4)
12345678910116. 多进程7. logging 消息重复问题多次循环调用程序时,日志出现第一条记录打印一条,第二次记录打印两条,依次类推,导致后续大量重复的日志输出。原因是:重复调用logging,由于logger的name是一样的,每次调用都会添加handler,多个handler就会打印多条同样的日志记录。解决办法:存在handler就不重复创建了,直接返回logger。这一篇csdn的博客可以作为参考:[Python logging 重复写日志问题](http://blog.csdn.net/huilan_same/article/details/51858817)```pythonlogger = logging.getLogger(logname)if not logger.handlers:balabala...return logger
- if path does not exist create 12if not os.path.exists(directory):os.makedirs(directory)
pythonic way to create 3d dict
1json_dict = defaultdict(lambda: defaultdict(dict))-
12from collections import defaultdict, Counterd = defaultdict(Counter)
Display image as grayscale using matplotlib
123456789import numpy as npimport matplotlib.pyplot as pltfrom PIL import Imagefname = 'image.png'image = Image.open(fname).convert("L")arr = np.asarray(image)plt.imshow(arr, cmap='gray')plt.show()
python的缩进是天使也是恶魔,尤其是使用vim的时候
不遵守pep8的都应该受惩罚
15.