实战:使用py2neo和pandas处理海事数据

2024-01-07 19:18

本文主要是介绍实战:使用py2neo和pandas处理海事数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

海事数据的格式

标签:
ship_ShipName,ship_MMSI,ship_BuildDate,ship_ShipTypeGroup,ship_ShipTypeLevel5SubGroup,ship_ShipType,ship_GroupCompany,ship_GroupCompanyCountry,ship_OperatorCompany,ship_OperatorCompanyCountry,ship_CountryOfEconomicBenefit,ship_DeadWeight,ship_GrossTonnage,ship_LengthLOA,ship_MouldWidth,ship_Draught,ship_LiquidCapacity

首先使用excel根据标签中的如下五个类别创建三元组形成ships.csv文件:

  1. ship_GroupCompany,
  2. ship_GroupCompanyCountry,
  3. ship_OperatorCompany,
  4. ship_OperatorCompanyCountry,
  5. ship_CountryOfEconomicBenefit

ships.csv文件的格式如下图:
在这里插入图片描述
有了三元组和原表格我们可以很方便添加数据到neo4j的数据库中。

函数

  1. createNode:在neo4j中创建节点
  2. createRelationship:在neo4j中创建节点的关系
  3. matchNode:在neo4j中匹配数据
  4. get_ship_properties:得到所有船的属性
  5. csv2df:将csv转为df
  6. df2neo:将df(从df中提取的数据)转为neo4j

代码

from py2neo import *
import os
import pandas as pd
import numpy as np# 数据库
graph = Graph('http://localhost:7474', username='neo4j', password='myneo4j')# 创建节点
def createNode(m_graph, m_label, m_attrs):# m_n = "_.name=" + "\'" + m_attrs['name'] + "\'"m_n = Noneif m_label == 'SHIP':m_n = "_.MMSI=" + "\'" + m_attrs['MMSI'] + "\'"elif m_label == 'COMPANY' or m_label == 'COUNTRY/REGION':m_n = "_.Name=" + "\'" + m_attrs['Name'] + "\'"matcher = NodeMatcher(m_graph)re_value = matcher.match(m_label).where(m_n).first()print(re_value)if re_value is None:m_node = Node(m_label, **m_attrs)n = graph.create(m_node)return n# print('Fail to create Node!!')return None# 创建两个节点的关系,如果节点不存在就不创建关系
def createRelationship(m_graph, m_label1, m_attrs1, m_label2, m_attrs2, m_r_name):reValue1 = matchNode(m_graph, m_label1, m_attrs1)reValue2 = matchNode(m_graph, m_label2, m_attrs2)if reValue1 is None or reValue2 is None:# print('reValue1: ', reValue1, 'reValue2: ', reValue2)# print('Fail to create relationship!!')return Falsem_r = Relationship(reValue1, m_r_name, reValue2)n = graph.create(m_r)return n# 查询节点,按照ID查询,无返回None
# def matchNodeById(m_graph, m_id):
#    matcher = NodeMatcher(m_graph)
#    re_value = matcher.get(m_id)
#    return re_value# 查询节点,按照name查询,无返回None
def matchNode(m_graph, m_label, m_attrs):# m_n = "_.name=" + "\'" + m_attrs['name'] + "\'"m_n = Noneif m_label == 'SHIP':m_n = "_.MMSI=" + "\'" + m_attrs['MMSI'] + "\'"elif m_label == 'COMPANY' or m_label == 'COUNTRY/REGION':m_n = "_.Name=" + "\'" + m_attrs['Name'] + "\'"# print(m_n)matcher = NodeMatcher(m_graph)re_value = matcher.match(m_label).where(m_n).first()return re_value# 查询节点,按照标签查询,无返回None
# def matchNodeByLabel(m_graph, m_label):
#     matcher = NodeMatcher(m_graph)
#     re_value = matcher.match(m_label)
#     return re_value# 从原本的表格中直接拿到数据并保存在字典中
def get_ship_properties(original_df):ships = {}for i in range(original_df.shape[0]):ship_properties = {'Name': str(original_df.loc[i, 'ship_ShipName']),'MMSI': str(original_df.loc[i, 'ship_MMSI']),'BuildDate': str(original_df.loc[i, 'ship_BuildDate']),'ShipTypeGroup': str(original_df.loc[i, 'ship_ShipTypeGroup']),'ShipTypeLevel5SubGroup': str(original_df.loc[i, 'ship_ShipTypeLevel5SubGroup']),'ShipType': str(original_df.loc[i, 'ship_ShipType']),'DeadWeight': str(original_df.loc[i, 'ship_DeadWeight']),'GrossTonnage': str(original_df.loc[i, 'ship_GrossTonnage']),'LengthLOA': str(original_df.loc[i, 'ship_LengthLOA']),'MouldWidth': str(original_df.loc[i, 'ship_MouldWidth']),'Draught': str(original_df.loc[i, 'ship_Draught']),'LiquidCapacity': str(original_df.loc[i, 'ship_LiquidCapacity'])}ships[ship_properties['MMSI']] = ship_properties# print(ships)return ships# csv转为df
def csv2df(file_name):df = pd.read_csv(file_name)# print(df.head())return df# df转到neo4j的数据库中
def df2neo(df, ships):diff_group = df.groupby('relation')for relation, df in diff_group:head = Nonetail = Nonehead_property = Nonetail_property = None# print('relation:', relation)df.reset_index(drop=True, inplace=True)# print(df)for i in range(df.shape[0]):if relation == 'GroupCompany' or relation == 'OperatorCompany':head = 'SHIP'head_property = ships[df.loc[i, 'head']]tail = 'COMPANY'tail_property = {'Name': df.loc[i, 'tail']}elif relation == 'CountryOfEconomicBenefit':head = 'SHIP'head_property = ships[df.loc[i, 'head']]tail = 'COUNTRY/REGION'tail_property = {'Name': df.loc[i, 'tail']}elif relation == 'GroupCompanyCountry' or 'CountryOfEconomicBenefit':head = 'COMPANY'head_property = {'Name': df.loc[i, 'head']}tail = 'COUNTRY/REGION'tail_property = {'Name': df.loc[i, 'tail']}# 本来是想对有单引号的数据进行处理,但发现很容易混乱,于是最后用excel把数据中的单引号全部替换掉了# head_property['Name'] = head_property['Name'].replace("'", '\\\'') # tail_property['Name'] = tail_property['Name'].replace("'",'\\\'')if tail_property['Name'] == 'Unknown' or tail_property['Name'] in (None, '', np.nan):continue # 空数据不进行添加# print('head: ', head, ', head_property: ', head_property, ', tail: ', tail, ', tail_property',#       tail_property)createNode(graph, head, head_property)createNode(graph, tail, tail_property)createRelationship(graph, head, head_property, tail, tail_property, relation)ship_df = csv2df('./ships.csv')
original_df = csv2df('./abc.csv')
ships = get_ship_properties(original_df)
df2neo(ship_df, ships)# 以下代码是对createNode函数和createRelationship函数的测试!
# label1 = 'Stock'
# attrs1 = {'name': '招商银行', 'code': '600036'}
# label2 = 'SecuritiesExchange'
# attrs2 = {'name': '上海证券交易所'}
# # 1. 创建节点
# createNode(graph, label1, attrs1)
# createNode(graph, label2, attrs2)
# m_r_name = '证券交易所'
# # 2. 添加关系
# reValue = createRelationship(graph, label1, attrs1, label2, attrs2, m_r_name)

参考

部分代码在张曙光老师的bilibili的neo4j课程基础上做出改动

这篇关于实战:使用py2neo和pandas处理海事数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/580962

相关文章

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

电脑提示xlstat4.dll丢失怎么修复? xlstat4.dll文件丢失处理办法

《电脑提示xlstat4.dll丢失怎么修复?xlstat4.dll文件丢失处理办法》长时间使用电脑,大家多少都会遇到类似dll文件丢失的情况,不过,解决这一问题其实并不复杂,下面我们就来看看xls... 在Windows操作系统中,xlstat4.dll是一个重要的动态链接库文件,通常用于支持各种应用程序

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安