Python数据帧在同一列中获取所有排列 [英] Python data Frame get all permutations in same column
问题描述
我有一个包含单词列表的python数据框.
I have a python data frame containing list of words.
Column Name
1. text1
2. text2
3. text3
我需要用空格分隔的单列中一次找到3个单词的数据帧中的所有排列.输出必须如下所示.
I need to find all permutations from the data frame with 3 words at a time in a single column seperated by space. The output has to look like below.
text1 text2 text3
text1 text3 text2
text2 text3 text1
text2 text1 text3
text3 text2 text1
text3 text1 text2
对此有任何帮助,不胜感激!!
Any help on this is appreciated!!
推荐答案
Itertools 一个>这是伟大的!具体来说, itertools.permutations
:
Itertools is great for this! Specifically, itertools.permutations
:
import itertools as it
df = pd.DataFrame({'col': ['text1', 'text2', 'text3']})
perms = it.permutations(df.col)
这将为您提供一个生成器perms
,该生成器将在您每次调用next(perms)
时为您提供下一个排列,例如for perm in perms:
或[perm for perm in perms]
之类的东西会自动执行.
This gives you a generator, perms
, that will give you the next permutation every time you call next(perms)
, something that things like for perm in perms:
or [perm for perm in perms]
does automatically.
请注意,如果数据框中有三个以上的元素,但一次只想排列三个,则可以在上面使用it.permutations(df.col, 3)
.还要注意,如果数据框中有很多元素,则将获得大量的排列.这是二项式排列数量等于n选择k"或N = n! / (k! * (n - k)!)
.
Note that if you have more than three elements in your dataframe, but only want permutations of three at a time, you would use it.permutations(df.col, 3)
in the above. Also note that you will get a TON of permutations if you have a lot of elements in your dataframe. It's the binomial "number of permutations equals n choose k", or N = n! / (k! * (n - k)!)
.
您可以通过以下方式获取所需的输出格式:
You can get the output format you want with something like:
result = '\n'.join([' '.join([s for s in perm]) for perm in perms])
print(result)
text1 text2 text3
text1 text3 text2
text2 text1 text3
text2 text3 text1
text3 text1 text2
text3 text2 text1
这篇关于Python数据帧在同一列中获取所有排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!