在Python中创建多个非数字列的相关性

发布于 2025-02-10 05:36:20 字数 1203 浏览 2 评论 0原文

我有一个很长的数据框架,我想知道每个元素的相关性,实际数据帧大约为40列宽,所以我在此处编写了此示例。

标识符1列2列3列4
1羊羊恐龙
2
3野猪,

想要的是3个新列,看起来像该

标识符var1var2 1 var2
1
1
1羊毛1狗恐龙
1绵羊
1牛恐龙1羊恐龙
1恐龙
2
3大象
3公野公猪
3野猪

最终我需要它们这样的原因是在Tableau中创建一个相关矩阵(

如果您还知道其他任何创建相关矩阵的方法)在Tableau中创建一个相关矩阵在所有这些变量中,请让我知道,这是我发现的最佳方法,但无论如何我仍然需要创建这个新表。

还有一个额外的东西,使它更加困难和有趣!有时,某些列会为空,如果发生这种情况,则应该停止而不继续。

提前致谢

I have a very long data frame, I want to know the correlations of each and every element, the actual data frame is about 40 columns wide, so I am writing this example here.

IdentifierColumn1Column2Column3Column4
1DogCowSheepDinosaur
2DogPig
3BullElephantBoar

What I want is 3 new columns that would look like this

IdentifierVar1Var2
1DogCow
1DogSheep
1DogDinosaur
1CowSheep
1CowDinosaur
1SheepDinosaur
2DogPig
3BullElephant
3BullBoar
3ElephantBoar

Eventually the reason I need them like this is to create a correlation matrix in tableau (It cannot be done in any other software)

If you guys know any other way to create a correlation matrix of all these variables, please let me know, this is the best way I found out but I still need to create this new table anyway.

And an extra to make it more difficult and interesting! Sometimes some of the columns will be empty, if that happens then it should stop and not continue.

Thanks in advance

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

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

发布评论

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

评论(1

日久见人心 2025-02-17 05:36:20
from itertools import combinations
data = pd.DataFrame(df.apply(lambda x: [x.Identifier, list(combinations(x.drop('Identifier'), 2))], axis=1).tolist()).explode(1)
df2 = pd.DataFrame(data[1].tolist(), index=data[0]).dropna(thresh=2)
df2.columns = ["Var1","Var2"]
df2.reset_index(inplace=True)
df2.rename(columns={0:"Identifier"}, inplace=True)
df2

输出:

    Identifier  Var1    Var2
0   1   Dog Cow
1   1   Dog Sheep
2   1   Dog Dinosaur
3   1   Cow Sheep
4   1   Cow Dinosaur
5   1   Sheep   Dinosaur
6   2   Dog Pig
7   3   Bull    Elephant
8   3   Bull    Boar
9   3   Elephant    Boar
from itertools import combinations
data = pd.DataFrame(df.apply(lambda x: [x.Identifier, list(combinations(x.drop('Identifier'), 2))], axis=1).tolist()).explode(1)
df2 = pd.DataFrame(data[1].tolist(), index=data[0]).dropna(thresh=2)
df2.columns = ["Var1","Var2"]
df2.reset_index(inplace=True)
df2.rename(columns={0:"Identifier"}, inplace=True)
df2

output:

    Identifier  Var1    Var2
0   1   Dog Cow
1   1   Dog Sheep
2   1   Dog Dinosaur
3   1   Cow Sheep
4   1   Cow Dinosaur
5   1   Sheep   Dinosaur
6   2   Dog Pig
7   3   Bull    Elephant
8   3   Bull    Boar
9   3   Elephant    Boar
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文