【问题标题】:How to add column values from one Data Frame to the other column in second Data Frame based on conditions in Python?如何根据 Python 中的条件将一个数据框中的列值添加到第二个数据框中的另一列?
【发布时间】:2021-06-22 16:45:25
【问题描述】:

df1 = pd.DataFrame(zip(l1), columns =['l1'])
df1.l2.value_counts()

df2 = pd.DataFrame(zip(l2), columns =['l2'])
df2.l2.value_counts()

我想根据 df1 中的值计数将列值从 l2 添加到 l1。例如

  • 如果 'bb_#2' 的值计数 df1'bb_#1' 的值计数,则所有的 'bb_# df2 中的 3' 应添加到 df1 中的 'bb_#2' 中,并将它们的名称也更改为 'bb_#2' 并且
  • 与上述 'aa_#3' 的逻辑相同
  • df2 中的 'cc_#2' & 'cc_#3' 应合并并添加到 df1 中的 'cc_#1' 中。

应在 df1 中检查条件,如果满足条件,则应将 df2 中 l2 的值添加到 df1 的 l1 列中

输出 这里也给出了

l1=['aa_#1', 'bb_#1', 'bb_#2', 'aa_#1', 'aa_#1', 'aa_#1', 'bb_#1','aa_#2','bb_#2','aa_#2','bb_#1','bb_#1','bb_#1','bb_#2','bb_#2','cc_#1','bb_#2','bb_#2', 'bb_#2','aa_#2','aa_#2','aa_#2', 'cc_#1','cc_#1','cc_#1','cc_#1']

如果有办法在 Python 中执行此操作,请告诉我。我有 10,000 行这样的行要从 l2 添加到 l1,我什至不知道如何开始。我对 Python 真的很陌生。

【问题讨论】:

    标签: python-3.x excel pandas dataframe


    【解决方案1】:

    这是一种不使用 pandas 的方法。 .count() 方法返回列表中项目的值计数。 .extend() 方法将另一个附加到现有列表的末尾。最后,将一个列表乘以一个整数会重复并连接它很多次。 ['a'] * 3 == ['a', 'a', 'a']

    def extend_list(l1, l2, prefixes, final_prefixes, suffix_1, suffix_2, suffix_3):
        for prefix in prefixes:
            if l1.count(f'{prefix}_{suffix_2}') < l1.count(f'{prefix}_{suffix_1}'):
                l1.extend([f'{prefix}_{suffix_2}'] * l2.count(f'{prefix}_{suffix_3}'))
        for final_prefix in final_prefixes:
            l1.extend([f'{final_prefix}_{suffix_1}'] * 
            (l2.count(f'{final_prefix}_{suffix_2)') + l2.count(f'{final_prefix}_{suffix_3}')))
    
    l1 = ['aa_#1','bb_#1','bb_#2','aa_#1','aa_#1','aa_#1','bb_#1','aa_#2','bb_#2','aa_#2','bb_#1','bb_#1','bb_#1','bb_#2','bb_#2','cc_#1']
    l2 = ['aa_#3','aa_#3','aa_#3','bb_#3','bb_#3','bb_#3','cc_#2','cc_#2','cc_#3','cc_#3']
    
    l1 = extend_list(l1, l2, ["aa", "bb"], ["cc", "dd"], "#1", "#2", "#3")
    
    

    【讨论】:

    • @Charles 从哪里读取数据?我注意到您在问题上使用了 Excel 标记。现在,我将更新我的答案,将 'aa_#1' 或 'bb_#2' 等参数化为函数输入。
    • 我做了一个小改动来容纳多个最终前缀。如果前缀有某种模式,您可以使用列表推导构造它们的列表。例如[f'#{x}' for x in range(1,11)] == ['#1', '#2', '#3', '#4', '#5', '#6', '#7', '#8', '#9', '#10']。见docs.python.org/3/tutorial/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    相关资源
    最近更新 更多