将数据帧转换为热图矩阵?
convert dataframe to the heatmap matrix?
我有一个 pandas 数据框,其结构如下:
df = pd.DataFrame({'entry': [['A','B','C'],['A','B','E','D'],['C'],['D','A', 'B'],['D','C','E'],['E','A']]})
给出:
entry
0 [A, B, C]
1 [A, B, E, D]
2 [C]
3 [D, A, B]
4 [D, C, E]
5 [E, A]
我想将其转换为 方阵,数据框中唯一符号的大小(在本例中为 5:'A','B','C','D','E') 其中每个交叉点是这对被一起看到的频率(就像这里 [A,B] 被一起看到 3 次, pair [D,A] - 只有一次。如果有 3 个或更多符号在一起,我希望考虑所有组合。)所以输出是这样的:
A B C D E
A 3 1 1 1
B 1 1
C 1 1
D 2
E
我是该领域的新手,尝试编写一个遍历所有组合的循环。条目中可能有任何数量的项目,这有问题。
如果您需要无序对,以下内容应该有效。
import pandas as pd
import itertools
# First get a DataFrame (or could be a Series) of the pairwise combinations in each row
combinations = df['entry'].apply(lambda x: list(itertools.combinations(sorted(x), 2)))
# Then get a list of unique values - A,B,C,D,E
unique_values = sorted(list(set(
symbol for symbol_list in df.values.flatten() for symbol in symbol_list)))
# Create empty dataframe
result = pd.DataFrame(columns=unique_values, index=unique_values)
# Iterate through symbols and fill dataframe
for symbol_pair in list(itertools.combinations(unique_values, 2)):
result.loc[symbol_pair[0], symbol_pair[1]] = combinations.apply(lambda x: symbol_pair in x).sum()
我有一个 pandas 数据框,其结构如下:
df = pd.DataFrame({'entry': [['A','B','C'],['A','B','E','D'],['C'],['D','A', 'B'],['D','C','E'],['E','A']]})
给出:
entry
0 [A, B, C]
1 [A, B, E, D]
2 [C]
3 [D, A, B]
4 [D, C, E]
5 [E, A]
我想将其转换为 方阵,数据框中唯一符号的大小(在本例中为 5:'A','B','C','D','E') 其中每个交叉点是这对被一起看到的频率(就像这里 [A,B] 被一起看到 3 次, pair [D,A] - 只有一次。如果有 3 个或更多符号在一起,我希望考虑所有组合。)所以输出是这样的:
A B C D E
A 3 1 1 1
B 1 1
C 1 1
D 2
E
我是该领域的新手,尝试编写一个遍历所有组合的循环。条目中可能有任何数量的项目,这有问题。
如果您需要无序对,以下内容应该有效。
import pandas as pd
import itertools
# First get a DataFrame (or could be a Series) of the pairwise combinations in each row
combinations = df['entry'].apply(lambda x: list(itertools.combinations(sorted(x), 2)))
# Then get a list of unique values - A,B,C,D,E
unique_values = sorted(list(set(
symbol for symbol_list in df.values.flatten() for symbol in symbol_list)))
# Create empty dataframe
result = pd.DataFrame(columns=unique_values, index=unique_values)
# Iterate through symbols and fill dataframe
for symbol_pair in list(itertools.combinations(unique_values, 2)):
result.loc[symbol_pair[0], symbol_pair[1]] = combinations.apply(lambda x: symbol_pair in x).sum()