python常用操作之代码操作大全
目录
- 列表操作大全(list operations)
- 列表分割x等分
- 两个列表取交集
- 字符串列表转数字型
- 字典操作大全(dictionary operations)
- 用dict2更新dict1
- 对比两个字典相同的键名
- 对比两个字典相同的键值对
- 将字典中的键按大小排序并生成一个新的字典
- 表格操作大全( DataFrame operations)
- 表格中某一列:成交编号中不在列表A中的值组成的新表
- 将只有两列a,b的dataframe转换成dictionary
- MySQL操作大全 (MySQL operations)
- python连接数据库
- 连接数据库后读取表格信息
- 自建查询表格函数
- 列出数据库所有的表格名称
- 查询表格的所有字段
- 根据DataFrame生成MySQL数据表
列表操作大全(list operations)
列表分割x等分
#设计一个函数,用来分解列表为x等分,再以字典形式返回
def slice_list(lista, x):
dicta = {}
n = len(lista)
group_size = n // x
random.shuffle(lista)
for i in range(x - 1):
start = i * group_size
end = (i + 1) * group_size
dicta[i] = lista[start:end]
dicta[x - 1] = lista[(x - 1) * group_size:]
return dicta
两个列表取交集
A = list(set(mm_list_concat.成交编号) & set(df_mm.deal_no)) #取交集
字符串列表转数字型
def strlist2float(strlist):
list=[]
for i in strlist:
list.append(float(i))
return list
字典操作大全(dictionary operations)
用dict2更新dict1
dict1 = {'a': 1, 'b': 2,'c': 2}
dict2 = {'c': 3, 'd': 4}
dict1.update(dict2)
print(dict1)
对比两个字典相同的键名
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 2, 'c': 4, 'd': 5}
common_keys = dict1.keys() & dict2.keys()
different_keys = dict1.keys() ^ dict2.keys()
print("共同的键:", common_keys)
print("不同的键:", different_keys)
对比两个字典相同的键值对
common_items = dict1.items() & dict2.items()
different_items = [(k, v1, v2) for k, v1 in dict1.items() for k2, v2 in dict2.items() if k == k2 and v1 != v2]
print("共同的键值对:", common_items)
print("不同的键值对:", different_items)
将字典中的键按大小排序并生成一个新的字典
可以使用以下方法:
original_dict = {'b': 2, 'a': 1, 'c': 3}
sorted_keys = sorted(original_dict.keys())
sorted_dict = {key: original_dict[key] for key in sorted_keys}
print(sorted_dict)
输出:{'a': 1, 'b': 2, 'c': 3}
在上述代码中,我们使用sorted()函数对原始字典的键进行排序,并将排序后的键按顺序构建新的字典sorted_dict。最终输出的结果就是按照键的大小排序的新字典。
请注意,字典是无序的数据结构,因此排序只会影响键的顺序,而不会改变字典中键值对的存储方式。
表格操作大全( DataFrame operations)
表格中某一列:成交编号中不在列表A中的值组成的新表
df_new = df[~df.成交编号.isin(A)]
将只有两列a,b的dataframe转换成dictionary
df_dict = df.set_index('a')['b'].to_dict()
MySQL操作大全 (MySQL operations)
python连接数据库
连接数据库后读取表格信息
自建查询表格函数
#自定义函数query_table,用来查询指定数据库的指定表格
def query_table(database,table):
host='localhost'
user='root'
password= password
port=3306
conn=create_engine('mysql+pymysql://{}:{}@{}:{}/{}'.format(user,password,host,port,database))
sql='select * from '+str(database)+'.'+str(table)
results=pd.read_sql(sql,conn)
return results
列出数据库所有的表格名称
import pymysql
# 列出所有的表
def list_table(localhost, username, password, database):
db = pymysql.connect(localhost, username, password, database, charset="utf8")
cursor = db.cursor()
cursor.execute("show tables")
table_list = [tuple[0] for tuple in cursor.fetchall()]
db.close()
return table_list
查询表格的所有字段
def list_col(localhost, username, password, database, tabls_name):
db = pymysql.connect(localhost, username, password, database, charset="utf8")
cursor = db.cursor()
cursor.execute("select * from %s" % tabls_name)
col_name_list = [tuple[0] for tuple in cursor.description]
db.close()
return col_name_list
根据DataFrame生成MySQL数据表
import pandas as pd
from sqlalchemy import create_engine
import pymysql as py
def create_mysql_table(df, table_name):
# 获取DataFrame的列名和数据类型
columns = df.dtypes.index.tolist()
dtypes = df.dtypes.values.tolist()
# 创建表的SQL语句
create_table_query = f"CREATE TABLE {table_name} ("
# 构建列的定义
for col, dtype in zip(columns, dtypes):
if 'object' in str(dtype):
max_length = df[col].astype(str).apply(len).max() # 获取列数据的最大长度
varchar_length = min(max_length, 255) # 限制VARCHAR长度最大为255
create_table_query += f"{col} VARCHAR({varchar_length}), "
elif 'datetime' in str(dtype):
create_table_query += f"{col} DATE, "
elif 'float' in str(dtype):
max_decimals = df[col].apply(lambda x: len(str(x).split('.')[-1])).max() # 获取浮点数小数点后的最大位数
float_length = min(max_decimals + 4, 38) # 限制FLOAT小数点后数据长度最大为38
create_table_query += f"{col} FLOAT({float_length}), "
elif 'int' in str(dtype):
create_table_query += f"{col} INT, "
elif 'bool' in str(dtype):
create_table_query += f"{col} TINYINT, "
else:
create_table_query += f"{col} TEXT, "
create_table_query = create_table_query.rstrip(', ') + ")"
# 返回创建表的SQL语句
return create_table_query