实战:使用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

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

k8s按需创建PV和使用PVC详解

《k8s按需创建PV和使用PVC详解》Kubernetes中,PV和PVC用于管理持久存储,StorageClass实现动态PV分配,PVC声明存储需求并绑定PV,通过kubectl验证状态,注意回收... 目录1.按需创建 PV(使用 StorageClass)创建 StorageClass2.创建 PV

Python版本信息获取方法详解与实战

《Python版本信息获取方法详解与实战》在Python开发中,获取Python版本号是调试、兼容性检查和版本控制的重要基础操作,本文详细介绍了如何使用sys和platform模块获取Python的主... 目录1. python版本号获取基础2. 使用sys模块获取版本信息2.1 sys模块概述2.1.1

Redis 基本数据类型和使用详解

《Redis基本数据类型和使用详解》String是Redis最基本的数据类型,一个键对应一个值,它的功能十分强大,可以存储字符串、整数、浮点数等多种数据格式,本文给大家介绍Redis基本数据类型和... 目录一、Redis 入门介绍二、Redis 的五大基本数据类型2.1 String 类型2.2 Hash

Redis中Hash从使用过程到原理说明

《Redis中Hash从使用过程到原理说明》RedisHash结构用于存储字段-值对,适合对象数据,支持HSET、HGET等命令,采用ziplist或hashtable编码,通过渐进式rehash优化... 目录一、开篇:Hash就像超市的货架二、Hash的基本使用1. 常用命令示例2. Java操作示例三