【问题标题】:Assigning pandas columns based on set of reference list根据参考列表集分配熊猫列
【发布时间】:2021-06-05 23:03:52
【问题描述】:

目标是将列main_frame 值分配给参考列表。

目前实现如下操作:

import pandas as pd

watchlist_ref = [['A1','AA2','A3'],
                ['B1','BC2','B3']]
upper_ref = ['A','B']
df = pd.DataFrame ({'tw':['A1','AA2','A3','B1','BC2','B3']})

for ls_str, ws in zip(watchlist_ref, upper_ref):
    df.loc[(df['tw'].str.contains('|'.join(ls_str), case=False)), 'main_frame'] = ws

下面的输出:

    tw main_frame
0   A1          A
1  AA2          A
2   A3          A
3   B1          B
4  BC2          B
5   B3          B

但是,有什么办法可以避免使用for-loop

【问题讨论】:

    标签: python pandas assign


    【解决方案1】:

    您可以创建一个字典,其中包含作为键的监视列表值和作为值的引用,然后使用 replaceregex=True 创建新列:

    d = {'|'.join(ls_str): ws for ls_str, ws in zip(watchlist_ref, upper_ref)}
    df['main_frame'] = df['tw'].replace(d, regex=True)
    

    结果:

         tw  main_frame
    0    A1           A
    1   AA2           A
    2    A3           A
    3    B1           B
    4   BC2           B
    5    B3           B
    

    【讨论】:

    • 我喜欢这种方法,因为它对watchlist_refupper_ref 之间的潜在错误排列非常有效。例如,而不是 ` ['A','B'], one can potentially wrongly arrange it as ['B' ,'A']` 在这种情况下是错误的。
    【解决方案2】:

    试试explode 然后map

    s = pd.Series(watchlist_ref,index=upper_ref).explode()
    df['new'] = df.tw.map(dict(zip(s,s.index)))
    df
    Out[175]: 
        tw new
    0   A1   A
    1  AA2   A
    2   A3   A
    3   B1   B
    4  BC2   B
    5   B3   B
    

    【讨论】:

      猜你喜欢
      • 2020-12-11
      • 2022-09-23
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 2020-08-08
      相关资源
      最近更新 更多