微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

基于 Pandas 规则的列合并

如何解决基于 Pandas 规则的列合并

我有一个包含来自 pubmed文章的数据集。数据框看起来像这样:

df = pd.DataFrame({"section_names":[["introduction","methods","section1","another section","discussion"],["introduction","discussion","other section","one  more section","conclusion"]],"sections":[[["intro text","another sentence"],["some text","some text","more text"],"some text"],"some text"]],[["intro text","more text","some text"]]]})

所以基本上,section_names 列具有文章中所有部分的名称。在“部分”列中,section_names 中的每个部分名称的列表中有实际文本。作为第一步,我想将每个部分都放在一列中。所以,我这样做了:

df_col = pd.DataFrame([dict(zip(*pair)) for pair in zip(df['section_names'],df['sections'])]):

resulting dataframe

NaN 是有意义的,因为这些部分不适用于特定列,对于每一列至少有一个非 NaN 值。对于很多不同版块名称文章,列数会急剧增加。在原始数据集中,我实际上有大约 10,000 列。

我现在想要的是合并列并拥有最多 4 列(介绍、方法、讨论、结论)。我想说:

在部分名称 methods 之后,合并所有其他部分,直到 discussionmethodsmethods 之后的所有合并直到 conclusiondiscussion

在我们的 df 中使用此规则,对于第一篇文章section1another section 将与 methods 合并。对于第二个条目,other sectionone more section 应与 discussion 合并。

我该怎么做?

解决方法

一种选择是根据所需列的位置创建列索引,然后将每个组的行聚合到列表中:

desired_columns = ['introduction','methods','discussion','conclusion']
new_df = df.groupby(df.columns.isin(desired_columns).cumsum(),axis=1).agg(
    lambda x: x.agg(
        lambda r: list(itertools.chain.from_iterable(r.dropna()))
                  or np.nan,axis=1)
)
new_df.columns = desired_columns

new_df

                     introduction                                                                        methods                                                                                discussion              conclusion
0  [intro text,another sentence]  [some text,some text,more text,some text]                                                                    [some text,some text]                     NaN
1  [intro text,another sentence]                                                         [some text,some text]  [some text,some text]

列索引是使用以下方法创建的:

df.columns.isin(desired_columns).cumsum()

产生如下组:

[1 2 2 2 3 3 3 4]

完整的工作示例:

import itertools

import numpy as np
import pandas as pd

df = pd.DataFrame({
    "section_names": [
        ["introduction","methods","section1","anothersection","discussion"],["introduction","discussion","othersection","onemoresection","conclusion"]],"sections": [
        [["introtext","anothersentence"],["sometext","sometext","moretext"],"sometext"],"sometext"]],[["introtext","moretext","sometext"]]]
})

df = pd.DataFrame(
    [dict(zip(*pair)) for pair in zip(df['section_names'],df['sections'])])

desired_columns = ['introduction',axis=1)
)
new_df.columns = desired_columns
print(new_df.to_string())

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?