如何在python中的多个TSV文件中连接具有相似ID的行?

时间:2018-09-24 15:04:13

标签: python pandas

我有三个带名称的tsv文件; file1.tsv,file2.tsv和file3.tsv

这三个tsv文件具有以下列名;

  • ID
  • 评论

现在,我想创建一个tsv文件,其中的每个ID都会通过检查三个文件来获取串联的“注释”字符串。

例如;

file1.tsv
ID            Comment
Anne Smith    Comment 1 of Anne smith
Peter Smith   Comment 1 of peter smith

file2.tsv
ID            Comment
John Cena     Comment 2 of john cena
Peter Smith   Comment 2 of peter smith

file3.tsv
ID            Comment
John Cena     Comment 3 of john cena
Peter Smith   Comment 3 of peter smith

结果文件应为;

results.tsv
ID            Comment
Anne Smith    Comment 1 of Anne smith
John Cena     Comment 2 of john cena. Comment 3 of john cena.
Peter Smith   Comment 1 of peter smith. Comment 2 of peter smith. Comment 3 of peter smith

我是熊猫新手。只是想知道我们是否可以使用Pandas或任何其他合适的库来执行串联操作,而不是从头开始编写。

3 个答案:

答案 0 :(得分:4)

假设您将tsv读入df1,df2,df3

df=pd.concat([df1,df2,df2]).groupby('ID').Comment.apply('. '.join)

答案 1 :(得分:1)

您可以只使用Pandas的read_csv函数,但是将sep参数设置为\t

如果在所有三个TSV文件上都使用此选项,则应该以三个数据帧结束。然后,您可以使用merge函数将它们组合为您想要的方式。

答案 2 :(得分:1)

为进一步扩展Wen的答案,最后一个循环不是很简单,但它可以工作...

Vue.component('menu-section', {
    props: ['menusection'],
    template: '<li>{{ menusection.name }}</li>'
})

Vue.component('menu-section-info', {
    props: ['menusectioninfo'],
    template: '#menusectioninfo-template'
})

new Vue({
        el:'#app',
    data: {
            // this will be retrieved using an ajax request
        menuSectionList: [
            { id: 1, name: 'Pizzas' },
            { id: 2, name: 'Burgers' },
            { id: 3, name: 'Wraps' },
            { id: 4, name: 'Drinks' },
            { id: 5, name: 'Sweets' }
        ]
    }
})

<script src="https://unpkg.com/vue"></script>

<div id="app">
        <ol>
            <menu-section v-for="item in menuSectionList"
                        v-bind:menusection="item"
                        v-bind:key="item.id">
            </menu-section>
        </ol>

        <div style="margin-top:20px;">
         <!-- The info here has been hardcoded, it should be retrieved using an ajax request when one of the sections has been clicked. The favourites link should also make and ajax request passing the selected section. -->
          <menu-section-info menusectioninfo="We sell the best burgers in the world!"></menu-section-info>
        </div>
</div>

<script type="text/x-template" id="menusectioninfo-template">
  <div>
    <div>{{ menusectioninfo }}</div>
    <div><a href="#">Click here to add section to your favourites list</a></div>
  </div>
</script>
相关问题