如何从Pandas DataFrame创建多个列组合?

发布于 2025-01-27 09:30:59 字数 473 浏览 2 评论 0原文

我将用图纸说明我的问题:

”“在此处输入图像说明”

我有一个Pandas DataFrame,其中13列6种不同类型。然后,我随机地想采用每种类型之一,并创建一个新表以执行后续分析。 因此,最后我想创建(3选择1) * 1 *(2选择1) *(2选择1) *(4选择1) * 1 = 1 = 48个pandas dataframe中的新dataframes。

这些列没有特定的名称,但可以例如:a1,a2,a3,b1,c1,c2,d1,d1,d2,e1,e2,e2,e3,e4,f1

有任何人一个想法如何在Python中实现此问题?

I’ll illustrate my problem with a drawing:

enter image description here

I have a pandas dataframe with 13 columns of 6 different types. Then I randomly want to take one of each type and create a new table to perform subsequent analyses.
So in the end I want to create (3 choose 1) * 1 * (2 choose 1) * (2 choose 1) * (4 choose 1) * 1 = 48 new dataframes out of one pandas dataframe.

The columns don't have specific names, but it could be for example: A1, A2, A3, B1, C1, C2, D1, D2, E1, E2, E3, E4, F1

Has anyone an idea how to implement this problem in Python?

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

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

发布评论

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

评论(1

断肠人 2025-02-03 09:30:59

如果您可以根据其类型将列名与列表分开,那么您的问题就会成为查找这些列表的笛卡尔产品的问题。找到笛卡尔产品后,您可以在其上迭代并使用列名的组合过滤您的数据框(有(3选择1) * 1 *(2选择1) *(2选择1) *(4选择1) * 1 = 48)。

A_cols = ['A1','A2','A3']
B_cols = ['B1']
C_cols = ['C1','C2']
D_cols = ['D1','D2']
E_cols = ['E1','E2','E3','E4']
F_cols = ['F1']

# column_combos is length 48
column_combos = pd.MultiIndex.from_product([A_cols,B_cols,C_cols,D_cols,E_cols,F_cols])
# out is a dictionary of 48 DataFrames
out = {';'.join(cols): df[[*cols]] for cols in column_combos}

If you can separate column names to lists according to their types, then your problem becomes a question of finding the Cartesian product of these lists. Once you find the Cartesian product, you can iterate over it and filter your DataFrame with a combination of column names (there are (3 choose 1) * 1 * (2 choose 1) * (2 choose 1) * (4 choose 1) * 1 = 48 of them).

A_cols = ['A1','A2','A3']
B_cols = ['B1']
C_cols = ['C1','C2']
D_cols = ['D1','D2']
E_cols = ['E1','E2','E3','E4']
F_cols = ['F1']

# column_combos is length 48
column_combos = pd.MultiIndex.from_product([A_cols,B_cols,C_cols,D_cols,E_cols,F_cols])
# out is a dictionary of 48 DataFrames
out = {';'.join(cols): df[[*cols]] for cols in column_combos}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文