可视化数据框中的各行和列之间的多个分类值如何差异

发布于 2025-02-10 20:45:31 字数 579 浏览 0 评论 0原文

我有以下数据框,其中每列代表索引中这些项目(a,b,…)中的分类算法,

df = pd.DataFrame(index = ['a', 'b', 'c', 'd', 'e', 'f', 'g'])
df['A'] = ['a1', 'a1', 'a2', 'a2', 'a3', 'a4', 'a4']
df['B'] = ['b2', 'b2', 'b2', 'b1', 'b4', 'b3', 'b3']
df['C'] = ['c4', 'c4', 'c4', 'c3', 'c2', 'c2', 'c1']
df:
    A   B   C
a   a1  b2  c4
b   a1  b2  c4
c   a2  b2  c4 
d   a2  b1  c3
e   a3  b4  c2
f   a4  b3  c2
g   a4  b3  c1

我想在每列中重新排序类别名称,以便我可以更好地评估索引项目是否被类似地分类。跨列。

有没有办法可以看到类别在各列之间的不同?类似于vendiagram。

先感谢您。

I have the following DataFrame where each column represents a categorization algorithm for the items in the index (a,b, …)

df = pd.DataFrame(index = ['a', 'b', 'c', 'd', 'e', 'f', 'g'])
df['A'] = ['a1', 'a1', 'a2', 'a2', 'a3', 'a4', 'a4']
df['B'] = ['b2', 'b2', 'b2', 'b1', 'b4', 'b3', 'b3']
df['C'] = ['c4', 'c4', 'c4', 'c3', 'c2', 'c2', 'c1']
df:
    A   B   C
a   a1  b2  c4
b   a1  b2  c4
c   a2  b2  c4 
d   a2  b1  c3
e   a3  b4  c2
f   a4  b3  c2
g   a4  b3  c1

I would like to reorder the category names in each column so that I can better assess whether the index items are being categorised similarly across columns.

Is there a way to visualise how the categories differ across columns? Something like a vendiagram.

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤千羽 2025-02-17 20:45:31

这是我对您有趣的问题的看法。

使用Python标准库 difflib 模块,该模块为计算Deltas提供帮助,您可以定义辅助功能。

from difflib import SequenceMatcher

# Define a simple helper function
def ratio(a, b):
    return SequenceMatcher(None, a, b).ratio()

一般的想法是使用唯一标识符(基于所有列)对行之间的相似性进行评分,并从最相似的行中对数据框进行排序。

# Create a column of unique identifiers: (a, a1b2c4) for instance
df["value"] = list(zip(df.index, df["A"] + df["B"] + df["C"]))

# Find similarities and assign ratio to each unique identifier
df = df.assign(
    match=df["value"].map(
        lambda x: {
            value: ratio(x[1], value[1])
            for value in df["value"]
            if x[0] != value[0] or ratio(x[1], value[1]) != 1
        }
    )
)

# Get best ratio key: (b, a1b2c4) for instance
df["key"] = df["match"].map(lambda x: max(x, key=x.get))

# Get best match ratio
df["ratio"] = df.apply(lambda x: round(x["match"][x["key"]] * 100), axis=1)

# Sort dataframe by best ratio and cleanup
df = (
    df.sort_values("ratio", ascending=False)
    .drop(columns=["value", "match", "key"])
    .drop(columns="ratio")
)
print(df)
# Output

然后,将任意颜色分配给第一行(整体)及其个体值,并通过每一行,并分配上一个颜色(如果相同)或新的颜色(两者都行本身和值),例如,行中的c2 ef具有相同的颜色。

COLORS = [
    "#F0A3FF", "#0075DC", "#FFA405", "#5EF1F2", "#FFFF00",
    "#E0FF66", "#FF5005", "#FFA8BB", "#2BCE48", "#993F00",
    "#F00300", "#19700C", "#00F405", "#4E61F2", "#FF90FF",
    "#E0FFFF", "#FF0005",
]

# Assign colors to rows and values homogenously
color_rows = {}
color_values = {}

for row in df.to_dict(orient="index").values():
    color = COLORS.pop(0)
    for value in row.values():
        if value not in color_rows:
            color_rows[value] = color
            color_values[value] = color
color_mapping = color_rows | color_values

最后,在jupyter笔记本电脑单元格中,运行:

df.style.applymap(lambda v: f"background-color: {color_mapping.get(v, '')}")

输出:

”在此处输入图像描述”

Here is my take on your interesting question.

Using Python standard library difflib module, which provides helpers for computing deltas, you can define a helper function.

from difflib import SequenceMatcher

# Define a simple helper function
def ratio(a, b):
    return SequenceMatcher(None, a, b).ratio()

The general idea is to rate similarities between rows using a unique identifier (based on all columns), and sort the dataframe from most similar to less similar rows.

# Create a column of unique identifiers: (a, a1b2c4) for instance
df["value"] = list(zip(df.index, df["A"] + df["B"] + df["C"]))

# Find similarities and assign ratio to each unique identifier
df = df.assign(
    match=df["value"].map(
        lambda x: {
            value: ratio(x[1], value[1])
            for value in df["value"]
            if x[0] != value[0] or ratio(x[1], value[1]) != 1
        }
    )
)

# Get best ratio key: (b, a1b2c4) for instance
df["key"] = df["match"].map(lambda x: max(x, key=x.get))

# Get best match ratio
df["ratio"] = df.apply(lambda x: round(x["match"][x["key"]] * 100), axis=1)

# Sort dataframe by best ratio and cleanup
df = (
    df.sort_values("ratio", ascending=False)
    .drop(columns=["value", "match", "key"])
    .drop(columns="ratio")
)
print(df)
# Output

enter image description here

Then, assign an arbitrary color to the first row (as a whole) and its individual values, and go through each row and either assign the previous color (if identical) or a new one (both to row itself and the values), so that, for instance, c2 in rows e and f has the same color.

COLORS = [
    "#F0A3FF", "#0075DC", "#FFA405", "#5EF1F2", "#FFFF00",
    "#E0FF66", "#FF5005", "#FFA8BB", "#2BCE48", "#993F00",
    "#F00300", "#19700C", "#00F405", "#4E61F2", "#FF90FF",
    "#E0FFFF", "#FF0005",
]

# Assign colors to rows and values homogenously
color_rows = {}
color_values = {}

for row in df.to_dict(orient="index").values():
    color = COLORS.pop(0)
    for value in row.values():
        if value not in color_rows:
            color_rows[value] = color
            color_values[value] = color
color_mapping = color_rows | color_values

And finally, in a Jupyter notebook cell, run:

df.style.applymap(lambda v: f"background-color: {color_mapping.get(v, '')}")

Output:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文