-
-
Save Dre1k23/5d6fbd940acee2ff087021b59bc97c8f to your computer and use it in GitHub Desktop.
graph
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
G = nx.Graph() | |
for skills in df['Ключевые навыки']: | |
# Проверяем тип данных | |
if isinstance(skills, str): | |
skills_list = skills.split(';') | |
for i in range(len(skills_list)): | |
for j in range(i+1, len(skills_list)): | |
# Добавляем ребро между навыками | |
G.add_edge(skills_list[i], skills_list[j]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Позиционирование узлов на плоскости | |
pos = nx.spring_layout(G) | |
# Создание списка координат узлов | |
node_x = [] | |
node_y = [] | |
for node in pos: | |
x, y = pos[node] | |
node_x.append(x) | |
node_y.append(y) | |
# Создание списка ребер | |
edge_x = [] | |
edge_y = [] | |
for edge in G.edges(): | |
x0, y0 = pos[edge[0]] | |
x1, y1 = pos[edge[1]] | |
edge_x.append(x0) | |
edge_x.append(x1) | |
edge_x.append(None) | |
edge_y.append(y0) | |
edge_y.append(y1) | |
edge_y.append(None) | |
# Визуализация графа | |
fig = go.Figure() | |
# Добавление узлов | |
fig.add_trace(go.Scatter(x=node_x, y=node_y, mode='markers', marker=dict(color='rgb(152, 0, 0)', size=10), | |
hoverinfo='text', text=list(pos.keys()))) | |
# Добавление ребер с подсветкой при наведении | |
fig.add_trace(go.Scatter(x=edge_x, y=edge_y, mode='lines', line=dict(color='rgb(125, 125, 125)', width=1), | |
hoverinfo='none', opacity=0.5)) | |
fig.update_layout(title='Граф связей навыков', showlegend=False, xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), | |
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)) | |
fig.show("notebook") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Создаем копию DataFrame, чтобы избежать изменения исходных данных | |
df_copy = df.copy() | |
# Предварительно заменяем NaN в столбце 'Ключевые навыки' на пустые списки | |
df_copy['Ключевые навыки'] = df_copy['Ключевые навыки'].fillna('').apply(lambda x: x.split(';') if isinstance(x, str) else []) | |
# Убираем строки с пустыми значениями "Ключевые навыки" | |
df_copy = df_copy[df_copy['Ключевые навыки'].apply(len) > 0] | |
# Создаем пустой граф | |
G = nx.Graph() | |
# Создаем пустой словарь для хранения количества упоминаний каждой пары навыков | |
skills_count = {} | |
# Проходим по каждой строке в DataFrame | |
for skills_list in df_copy['Ключевые навыки']: | |
# Подсчитываем частоту упоминания каждой пары навыков и добавляем в словарь | |
for i, skill1 in enumerate(skills_list): | |
for skill2 in skills_list[i+1:]: | |
if (skill1, skill2) in skills_count: | |
skills_count[(skill1, skill2)] += 1 | |
else: | |
skills_count[(skill1, skill2)] = 1 | |
# Устанавливаем порог совместной встречаемости | |
threshold = 50 | |
# Добавляем узлы и ребра в граф | |
for (skill1, skill2), weight in skills_count.items(): | |
if weight >= threshold: | |
G.add_edge(skill1, skill2, weight=weight) | |
# Определяем позиции узлов на плоскости для визуализации | |
pos = nx.spring_layout(G) | |
# Определяем координаты узлов | |
node_x = [pos[node][0] for node in G.nodes()] | |
node_y = [pos[node][1] for node in G.nodes()] | |
node_text = [f'{node}<br>Встречаемость: {G.degree(node)}' for node in G.nodes()] | |
# Определяем связи между узлами | |
edge_x = [] | |
edge_y = [] | |
for edge in G.edges(): | |
x0, y0 = pos[edge[0]] | |
x1, y1 = pos[edge[1]] | |
edge_x.append(x0) | |
edge_x.append(x1) | |
edge_x.append(None) # Добавляем None для разделения линий | |
edge_y.append(y0) | |
edge_y.append(y1) | |
edge_y.append(None) | |
# Создаем объект фигуры Plotly | |
fig = go.Figure() | |
# Добавляем узлы и ребра к графу | |
fig.add_trace(go.Scatter(x=node_x, y=node_y, mode='markers', name='Навык', text=node_text, hoverinfo='text', marker=dict(size=10))) | |
fig.add_trace(go.Scatter(x=edge_x, y=edge_y, mode='lines', name='Связь', line=dict(color='gray', width=0.5))) | |
# Настраиваем внешний вид графа | |
fig.update_layout(title=f'Граф навыков вакансий (порог совместной встречаемости: {threshold})', showlegend=False, hovermode='closest') | |
# Отображаем граф | |
fig.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment