列和行与另一列中的公共值串联 [英] Columns and rows concatenation with a commun value in another column
问题描述
在下表中,我想将 Tri_gram_sents
列和 Value
列连接在一起,然后将 sentence 列中具有相同编号的所有行连接在一起代码>.
In the below mentioned table, I want to concatenate the columns Tri_gram_sents
and Value
together and then all rows which has the same number in column sentence
.
Tri_gram_sents Value sentence
(('<s>', '<s>'), 'ABC') 0.161681 1
(('<s>', 'ABC'), 'ABC') 0.472973 1
(('ABC', 'ABC'), 'ABC') 0.305732 1
(('ABC', 'ABC'), 'ABC') 0.005655 1
(('ABC', 'ABC'), '</s>') 0.434783 1
(('ABC', '</s>'), '</s>') 0.008547 1
(('<s>', '<s>'), 'DEF') 0.111111 2
(('<s>', 'DEF'), 'DEF') 0.039474 2
(('DEF', 'DEF'), 'DEF') 0.207317 2
(('DEF', 'DEF'), 'DEF') 0.074803 2
(('DEF', 'DEF'), '</s>') 0.037940 2
(('DEF', '</s>'), '</s>') 0.033163 2
(('<s>', '<s>'), 'GHI') 0.250000 3
(('<s>', 'GHI'), 'GHI') 0.103316 3
(('GHI', 'GHI'), 'GHI') 0.024155 3
(('GHI', 'GHI'), '</s>') 0.028302 3
(('GHI', '</s>'), '</s>') 0.117647 3 `
对于上面的一组行,我将在另一个表中总共得到 3 行,并且我的预期输出看起来:
For above set of rows, I will get a total of 3 rows in another table and my expected output looks:
(('<s>', '<s>'), 'ABC') 0.161681 (('<s>', 'ABC'), 'ABC') 0.472973 (('ABC', 'ABC'), 'ABC') 0.305732 (('ABC', 'ABC'), 'ABC') 0.005655 (('ABC', 'ABC'), '</s>') 0.434783 (('ABC', '</s>'), '</s>') 0.008547
(('<s>', '<s>'), 'DEF') 0.111111 (('<s>', 'DEF'), 'DEF') 0.039474 (('DEF', 'DEF'), 'DEF') 0.207317 (('DEF', 'DEF'), 'DEF') 0.074803 (('DEF', 'DEF'), '</s>') 0.037940 (('DEF', '</s>'), '</s>') 0.033163
(('<s>', '<s>'), 'GHI') 0.250000 (('<s>', 'GHI'), 'GHI') 0.103316 (('GHI', 'GHI'), 'GHI') 0.024155 (('GHI', 'GHI'), '</s>') 0.028302 (('GHI', '</s>'), '</s>') 0.117647
推荐答案
您可以使用 groupby
和 join
来创建预期的输出.一种方法是从 Tri_gram_sents
和 Value
列创建一个 to_join
列,然后 agg
这个列:
You can use groupby
and join
to create the expected output. One way is to create a column to_join
from the columns Tri_gram_sents
and Value
, and then agg
this column:
df['to_join'] = df['Tri_gram_sents'] + ' ' + df['Value'].astype(str)
ser_output = df.groupby('sentence')['to_join'].agg(' '.join)
或者您可以在一行中完成所有操作,而无需使用 apply
创建列:
Or you can do everything in one line without create the column with apply
:
ser_output = (df.groupby('sentence').apply(
lambda df_g: ' '.join(df_g['Tri_gram_sents']+' '+df_g['Value'].astype(str))))
你得到ser_output
:
sentence
1 (('<s>', '<s>'), 'ABC') 0.161681 (('<s>', 'ABC...
2 (('<s>', '<s>'), 'DEF') 0.111111 (('<s>', 'DEF...
...
第一个元素看起来像预期的那样:
where the first element looks as expected:
"(('<s>', '<s>'), 'ABC') 0.161681 (('<s>', 'ABC'), 'ABC') 0.472973 (('ABC', 'ABC'), 'ABC') 0.305732 (('ABC', 'ABC'), 'ABC') 0.005655 (('ABC', 'ABC'), '</s>') 0.434783 (('ABC', '</s>'), '</s>') 0.008547"
这篇关于列和行与另一列中的公共值串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!