Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #https://www.cian.ru/sale/flat/281946132/
- #https://www.cian.ru/sale/flat/281271977/
- #https://www.cian.ru/sale/flat/281748776/
- import pyvis
- from uuid import uuid4
- from pyvis.network import Network
- net = Network() # создаём объект графа
- import pandas as pd
- df = pd.DataFrame({'ID':[1,2,3,4,5,6],
- 'First Name':['Felix', 'Jean', 'James', 'Daphne', 'James', 'Peter'],
- 'Family Name': ['Revert', 'Durand', 'Wright', 'Hull', 'Conrad', 'Donovan'],
- 'Phone number': ['+33 6 12 34 56 78', '+33 7 00 00 00 00', '+33 6 12 34 56 78', '+33 6 99 99 99 99', '+852 0123 4567', '+852 0123 4567'],
- 'Email': ['felix.revert@gmail.com', 'jean.durand@gmail.com', 'j.custom@gmail.com', pd.np.nan, 'j.custom@gmail.com', pd.np.nan]})
- column_edge = 'Phone number'
- column_ID = 'ID'
- data_to_merge = df[[column_ID, column_edge]].dropna(subset=[column_edge]).drop_duplicates() # select columns, remove NaN
- # To create connections between people who have the same number,
- # join data with itself on the 'ID' column.
- data_to_merge = data_to_merge.merge(
- data_to_merge[[column_ID, column_edge]].rename(columns={column_ID:column_ID+"_2"}),
- on=column_edge
- )
- # By joining the data with itself, people will have a connection with themselves.
- # Remove self connections, to keep only connected people who are different.
- d = data_to_merge[~(data_to_merge[column_ID] == data_to_merge[column_ID + "_2"])] \
- .dropna()[[column_ID, column_ID + "_2", column_edge]]
- # To avoid counting twice the connections (person 1 connected to person 2 and person 2 connected to person 1)
- # we force the first ID to be "lower" then ID_2
- d.drop(d.loc[d[column_ID + "_2"] < d[column_ID]].index.tolist(), inplace=True)
- # добавление узлов
- net.add_nodes(
- df, # node ids
- label=['Table1', 'Table2', 'Table3', 'Table4', 'TAble5'], # node labels
- # node titles (display on mouse hover)
- title=['Main node', 'Just node', 'Just node', 'Just node', 'Node with self-loop'],
- color=['#d47415', '#22b512', '#42adf5', '#4a21b0', '#e627a3'] # node colors (HEX)
- )
- # добавляем тот же список узлов, что и в предыдущем примере
- net.add_edges([])
- net.show('graph.html')
- """import plotly.express as px
- import datapane as dp
- location_df = dp.Blob.get(name='location_df', owner='khuyentran1401').download_df()
- m = px.scatter_geo(location_df, lat='latitude', lon='longitude',
- color='total_stars', size='forks',
- hover_data=['user_name','followers'],
- title='Locations of Top Users')
- m.show()"""
- """import datapane as dp
- import pandas as pd
- import numpy as np
- df = pd.DataFrame(
- {
- "A": np.random.normal(-1, 1, 5),
- "B": np.random.normal(1, 2, 5),
- }
- )
- table = dp.DataTable(df,)
- app = dp.App(table)
- app.save(path="simple-table.html")"""
- import networkx as nx
- G = nx.from_pandas_edgelist(df=d, source=column_ID, target=column_ID+'_2', edge_attr=column_edge)
- G.add_nodes_from(nodes_for_adding=df.ID.tolist())
- nx.draw(G)
- import matplotlib.pyplot as plt
- import pyvis
- from uuid import uuid4
- import networkx as nx
- from pyvis.network import Network
- #net = Network() # создаём объект графа
- df = pd.read_excel("example_uuid.xlsx")
- G = nx.Graph() # создаём объект графа
- fig = plt.figure()
- # определяем список узлов (ID узлов)
- nodes = []
- for col in df:
- for i in df[col].unique():
- nodes.append(i)
- """for val in col[1]:
- print(val)"""
- #nodes.append(val)
- stop = 0
- # определяем список рёбер
- # список кортежей, каждый из которых представляет ребро
- # кортеж (id_1, id_2) означает, что узлы id_1 и id_2 соединены ребром
- #edges = [(1, 2), (1, 3), (2, 3), (2, 4), (3, 5), (5, 5)]
- edges = []
- for i in range(len(nodes) - 1):
- edges.append((nodes[i], nodes[i + 1]))
- # добавляем информацию в объект графа
- G.add_nodes_from(nodes)
- G.add_edges_from(edges)
- # рисуем граф и отображаем его
- nx.draw(G, with_labels=True, font_weight='bold')
- plt.show()
- stop = 0
- """***HELPFUL LINKS***
- https://habr.com/ru/company/vk/blog/522094/
- https://habr.com/ru/company/ruvds/blog/705368/
- https://scikit-learn.org/stable/auto_examples/tree/plot_unveil_tree_structure.html#sphx-glr-auto-examples-tree-plot-unveil-tree-structure-py
- https://machinelearningmastery.ru/getting-started-with-graph-analysis-in-python-with-pandas-and-networkx-5e2d2f82f18e/
- https://github.com/FelixChop/MediumArticles/blob/master/Graph_analysis_Python.ipynb"""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement