目录
1.获取工作目录和设置工作目录
2.获取日期处理
3.列表的倒排序
4.使用apply处理 两个值的代码
5.断言函数 assert
6.yield生成器
7.获取程序运行时间
8.动态生成变量
9.数据可持续化操作
10.数据运行时间2
11.创建目录
12.删除无用的数据
13.字符串格式化
14.zip自动生成字典
15.各种包的离线下载地址
16.路径的设置
17.数据添加ignore_index的使用技巧
18.删除nan的总结
19.批量重命名
20.nohup的使用
21.reset_index的使用
import os
# 查看目录下的文件
print(os.listdir(PATH) l
# 查看当前工作目录
retval = os.getcwd()
print ("当前工作目录为 %s" % retval)
# 修改当前工作目录
os.chdir( path )
# 查看修改后的工作目录
retval = os.getcwd()
#获取毫秒级别的时间
from datetime import *
dt = datetime.now()
dt.strftime('%Y-%m-%d-%H-%M-%S.%f')
import time,datetime
#字符串转化为时间类型
end_date = datetime.datetime.strptime('2018-07-01', '%Y-%m-%d')
# 获取当前时间
today = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) #方法一
from datetime import datetime, date, timedelta
# 今天
today = (datetime.today()).strftime('%Y%m%d') #方法2
print(today);
# 明天
data_next= (datetime.today() + timedelta(1)).strftime('%Y%m%d');
print(data_next);
# 30天后
data_30= (datetime.today() + timedelta(30)).strftime('%Y%m%d');
print(data_30);
train_periods = pd.read_csv('../input/periods_train.csv', parse_dates=['date_from', 'date_to'])
# 两个日期差多少天
all_periods['days_up'] = all_periods['date_to'].dt.dayofyear - all_periods['date_from'].dt.dayofyear
List= [1,2,3,4,5,6]
List[::-1]
import numpy as np
import pandas as pd
df = pd.DataFrame ({
'a' : np.random.randn(6),
'b' : ['foo', 'bar'] * 3,
'c' : np.random.randn(6)}
)
print(df)
def my_test(a, b):
return a + b
df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1)
print (df)
如何判断True or False np.NaN 默认为False
if valus:
print('yes')
else:
print('no')
x = 23
assert x < 0
assert x%2== 0
def fab(max):
n, a, b = 0, 0, 1
while n < max:
yield b
import time
from datetime import timedelta
def get_time_dif(start_time):
"""获取已使用时间"""
end_time = time.time()
time_dif = end_time - start_time
return timedelta(seconds=int(round(time_dif)))
start_time = time.time()
main() # 运行程序
time_dif = get_time_dif(start_time)
print("Time usage:", time_dif)
# 时间的形式:Time usage: 0:09:35
names = locals()
for i in range(1, 5):
names['x%s' % i] = i
if i ==1:
X_end = names['x%s' % i]
else:
X_end = X_end + names['x%s' % (i)]
import pickle
def main():
hjp_list = [123, 456, 789, 'test']
with open('hjp_list.pkl', 'wb') as pickle_file: # 导入本地
pickle.dump(hjp_list, pickle_file)
with open('hjp_list.pkl', 'rb') as pickle_file: # 加载本地数据
my_new_list = pickle.load(pickle_file)
print(my_new_list)
if __name__ == '__main__':
main()
#建模固定模块
import gc
from contextlib import contextmanager
import time
@contextmanager
def timer(title):
t0 = time.time()
yield
print("{}:使用时间为{:.0f}s".format(title, time.time() - t0))
#用法:
with timer("导入数据"):
main() '''这样就可以看到这段代码运行的时'''
if not os.path.exists('gen_data'):
os.mkdir('gen_data')
# 删除缺失率超过90%的列
good_cols = list(train.columns)
for col in train.columns:
rate = train[col].value_counts(normalize=True, dropna=False).values[0]
if rate > 0.9:
print(col)
name = 'hjp';name1 = 'python'
# 三种方式 推荐第三种
text1 = 'hello %s' %(name )
text2 = 'hello {}'.format(name )
text2 = 'hello {0},{1}'.format(name,name1 )
text3 = f'hello {name}'
x=['bob','tom','kitty']
y=[80,90,95]
d=dict(zip(x,y))
print(d)
各种包的下载地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/ 在谷歌浏览器中下载
root_dir = 'data/cnews'
path_dir = os.path.join(base_dir, 'train.csv')
data=pd.concat([train, test], ignore_index=True)
res = res.append(count, ignore_index=True)
#删除NaN值得汇总
df.dropna()
df.dropna(axis='columns')
df.dropna(how='all')
df.dropna(thresh=2)
df.dropna(subset=['name', 'born'])
df.dropna(inplace=True)
#字段名称重命名
print('Compute average')
avg_cc_bal = cc_bal.groupby('SK_ID_CURR').mean()
avg_cc_bal.columns = ['cc_bal_' + f_ for f_ in avg_cc_bal.columns]
1.例子:
nohup python test.py &
2.查看守护进程
ps -ef | grep python
3.kill进程
kill -s 9 xxxxx
reset_index(drop=True)
list_sample1 =[['我','喜欢','你'],['我','爱','你'],['我','疼着','你']]
flattened1 =[x for tup in list_sample1 for x in tup]
flist = [[x for x in tup] for tup in list_sample1 ]
import os
os.path.join('xxxx','xxxx','xxxx')
seq =[1,2,3,4,5]
result =list(map(lambda var:var*2,seq))
print(result)
seq =[1,2,3,4,5]
result =list(filter(lambda var:var>2,seq))
print(result)