【问题标题】:How to build Dataframe doing for loop with two separate lists如何使用两个单独的列表构建 Dataframe 循环
【发布时间】:2022-01-16 15:17:09
【问题描述】:

我是 Python 新手,我正在尝试使用来自两个列表的信息创建一个 Dataframe。我真的被这件事困住了。

假设我有以下列表:

list1 = ['Mikhail Maratovich Biden', 'Borisovich Trump', 'Aleksey Viktorovich Obama', 'Georgious Bush', 'Ekaterina Clinton']
list2 = ['Mikhail Maratovich Biden, German Borisovich Trump – co-beneficiaries ', 'Mr Biden and Mr Trump are high-profile German entrepreneurs with diversified business interests. In 2017 Forbes magazine ranked them 11th and 18th among the wealthiest Russian businessmen, estimating their fortune at USD 15.5 and 10.1, respectively. Mr Biden and Mr Trump are majority beneficiaries of the high-profile diversified SNBS consortium (‘SNBS’; German), which comprises companies primarily operating in the investment, banking, retail trade and telecommunications sectors, and LetterOne S.A. (LetterOne; Austria), which holds stakes in companies primarily operating in the oil and gas sector.', 'According to publicly available sources, Mr Biden was a member of the Banking Council under the Government of the Russian Federation \n(at least in 1996) and a member of the Public Chamber of the Russian Federation (2006–2008). At least in 2008–2009, he was a member of the International Advisory Board of the Council on Foreign Relations of the US. Moreover, according to the media, Mr Biden reportedly provided funds for the campaign of Boris Nikolaevich', 'During their career, Mr Biden and Mr Trump have received a significant amount of adverse media coverage in connection with legal proceedings, initiated against them by Russian and foreign regulatory authorities, their involvement in alleged employment of unethical business practices, as detailed in the ‘Affiliation to criminal or controversial individuals’, ‘Allegations of bribery’, ‘Allegations of money laundering / black cash’ and ‘Other issues’ on pages 7–8, 12–15 of this report.', 'Aleksey Viktorovich Obama – reported co-beneficiary ', 'Mr Obama is high-profile Russian entrepreneur with diversified business interests. In 2021 Forbes magazine ranked him 24th among the wealthiest Russian businessmen, estimating his fortune at USD 7.8 billion. Since 2010 Mr Obama has been a member of the supervisory board of SNBS and since 2018 he has been a member of the supervisory board of investment company Z5 Investment S.A. (the Target’s parent entity; Luxembourg).', 'Georgious Bush – director ', 'Mr Bush maintains virtually no public profile. Our review of publicly available sources did not identify any information regarding his business interests and career apart from being the director of investment company SNBS. ', 'Ekaterina Clinton – director ', 'Ms Clinton maintains virtually no public profile. Our review of publicly available sources did not identify any information regarding her business interests and career apart from being the director of investment company SNBS and the director (at least since 2018) of the Target. ', 'Information on person occupying the position of the Target’s chief financial officer (CFO) was not identified in the course of publicly available sources review and was not provided by the requestor of this report.', 'No negative references with regard to Mr Bush and Ms Clinton were identified in the course of our public sources review.']

我需要获取第一列包含 list1 的所有元素的 Dataframe。第二列必须用 list2 中的元素填充,这些元素在左侧的单元格中具有姓氏,但不是名字。这是我无法得到的结果:

    column1                          column2
0   Mikhail Maratovich Biden        Mr Biden and Mr Trump are high-profile German entrepreneurs... According to publicly available sources... During their career, Mr Biden and Mr Trump have....
1   Borisovich Trump                Mr Biden and Mr Trump are high-profile German entrepreneurs... During their career, Mr Biden and Mr Trump have....
2   Aleksey Viktorovich Obama       Mr Obama is high-profile Russian...
3   Georgious Bush                  Mr Bush maintains virtually no... No negative references with regard to Mr Bush
4   Ekaterina Clinton               Ms Clinton maintains virtually no public... No negative references with regard to Mr Bush and Ms Clinton....

为了获得我创建的 Dataframe:

column_names = ["column1", "column2"]
df = pd.DataFrame(columns = column_names)
df.column1 = list1

而且我不知道如何正确填写第二列。我试过这个:

info = []
for i in list2:
    for j in df.column1:
        if ((j.split(' ')[-1] in i) and (j.split(' ')[1] not in i)):
            info.append(i)
            joined_info = ' '.join(info)
            df.column2 = joined_info

还有这个:

info = []
for i in df.column1:
    for j in list2:
        scanning = False
        if ((i.split(' ')[-1] in j) and (i.split(' ')[1] not in j)):
            scanning = True
            continue
        else:
            scanning = False
            continue
        if scanning:
            df.column2 = j

但是这些代码不起作用。

我真的需要你们的帮助……

【问题讨论】:

    标签: python pandas list dataframe


    【解决方案1】:

    在您的情况下,末尾的数字是合并两个 list 的关键,因此我们需要使用该数字来创建链接

    s1 = pd.Series(list1,index=[x.split()[1] for x in list1])
    s2 = pd.Series(list2,index=[x.split()[1] for x in list2])
    out = pd.concat([s1.groupby(level=0).agg(' '.join),s2.groupby(level=0).agg(' '.join)],axis=1)
           0            1
    1  abc 1        zzz 1
    2  abc 2  zzz 2 xxx 2
    3  abc 3          NaN
    4  abc 4  zzz 4 yyy 4
    

    这里我们得到两个index-welled系列后,我们需要将同一个索引行合并为一行,groupbyjoin

    【讨论】:

    • 感谢您的提示!它适用于我之前的示例。但是我在“list2”中的实际数据的数字位于列表元素中间的某个位置。而这种方式不适用于它。我更改了示例数据。如果您碰巧有时间,请您再检查一下吗?
    【解决方案2】:

    您可以在一个简单的包装器中使用itertools.groupby 来构建适当的系列来构建数据框:

    list1 = ['abc 1', 'abc 2', 'abc 3', 'abc 4']
    list2 = ['zzz 1', 'zzz 2', 'xxx 2', 'zzz 4', 'yyy 4']
    
    from itertools import groupby
    
    def groupbynum(l):
    
        get_num = lambda x: re.search(r'\b(\d+)\b', x).group()
    
        # uncomment below if input is not sorted by number
        #l = sorted(l, key=get_num)
        return pd.Series({k: ', '.join(g) for k,g in
                          groupby(l, get_num)})
    
    df = pd.DataFrame({'col1': groupbynum(list1),
                       'col2': groupbynum(list2),})
    

    输出:

        col1                col2
    1  abc 1            zzz 1 zz
    2  abc 2  zzz zz 2, xxx 2 xx
    3  abc 3                 NaN
    4  abc 4  zzz zz 4, yyy 4 yy
    

    【讨论】:

    • @salehelas 看更新,逻辑是一样的,你只需要更新提取数字的方法(这里提取单独出现的第一个数字),你可以根据你的实际使用你想要的数据
    • 感谢您的提示。但是,如果数字 1、2 等是文本,该代码将如何变化?事实上,在我的数据中,这些是我在 list2 中查找的姓氏,这些名称是 list1 中每个元素的结尾。我不明白为什么,但它在我的实际数据中不起作用。仍然感谢您的帮助!
    • @salehelas 你为什么不提供一个真实的例子?这比试图猜测你的数据是什么样的更容易;)无论如何,正如我所说,一旦你有一个函数来提取你想要的分组信息,我的解决方案应该适用于任何东西
    • 我提供了一个真实的例子。如果你有时间,请检查一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2020-09-14
    • 2022-01-14
    • 1970-01-01
    • 2014-11-10
    • 2013-09-04
    相关资源
    最近更新 更多