读取MongoDB中的表
from pymongo import MongoClient
import pandas as pd
client = MongoClient('IP地址', 27017)
db = client['AOI']
collection = db['表名'] #替换为实际的名称
document = collection.find({'time':{'$gte':'2023-08-15 15:26:06'}})#筛选数据
df = pd.DataFrame(list(document))#转换为python常用的dataframe
# df = df[(df["time"] >= '2023-08-15 15:26:06')]
df["marks"] = df["marks"].astype('str')
df = df[df["marks"].str.contains("name")] #筛选数据
df = df.loc[:, ['_id', 'id', 'marks', 'time']] #选择想要的列
df.to_csv('path.csv', index=False)
Dataframe合并:
- 横向合并(增加列数)(跟据共同列来合并,如果有不同列则添加列)
(数据库的某些表数据太多无法保存到本地,直接merge取交集)
on=['串号']: 根据共同列进行合并,一定要保证有相同列名,不然会报错。
how='inner':取交集
df1 = pd.read_csv('D:\df1.csv', encoding='gbk')
df2 = pd.read_csv('D:\df2.csv', encoding='gbk')
df_merge = pd.merge(df1, df2, on=['串号'], how='inner')
df_merge.to_csv('D:\df3.csv')
-
纵向合并(增加行数)
merge_df = pd.concat([df1, df2], ignore_index=True)
merge_df.to_csv('D:\df_merge.csv', index=False)
Dataframe去重:(我发现老是去重失败,不知道为啥)
df = pd.read_csv('D:\AOI\df_merge_expert.csv', encoding='gbk')
df.drop_duplicates(keep='first', inplace=True)
df.to_csv('D:\AOI\df_merge_expert1.csv', index=False)