读取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合并:
1. 横向合并(增加列数)(跟据共同列来合并,如果有不同列则添加列)
(数据库的某些表数据太多无法保存到本地,直接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')
2. 纵向合并(增加行数)文章来源:https://www.toymoban.com/news/detail-684594.html
merge_df = pd.concat([df1, df2], ignore_index=True)
merge_df.to_csv('D:\df_merge.csv', index=False)
Dataframe去重:(我发现老是去重失败,不知道为啥)文章来源地址https://www.toymoban.com/news/detail-684594.html
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)
到了这里,关于MongoDB +Dataframe+excel透视表的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!