【问题标题】:Modify a Data Frame column with list comprehension使用列表理解修改数据框列
【发布时间】:2016-03-07 14:04:07
【问题描述】:

我有一个包含大约 90k 个字符串的列表和一个包含多列的数据框,我有兴趣检查列表的字符串是否在 column_1 中,以及它是否在 column_2 中分配了相同的值。

我可以这样做:

for i in range(len(my_list)):
    item = list[i]
    for j in range(len(df)):
         if item == df['column_1'][j]:
             df['column_2'][j] = item

但我宁愿避免嵌套循环

我试过了

for item in my list:
    if item in list(df['column _1']):
          position = df[df['column_1']==item]].index.values[0]
          df['column_2'][position]  = item

但我认为这个解决方案更慢更难阅读,这个操作可以通过简单的列表理解来完成吗?

编辑。

第二种解决方案要快得多,大约一个数量级。 这是为什么?似乎在那种情况下它必须搜索两次马赫:

这里:

if item in list(df['column _1'])

这里:

possition = df[df['column_1]=='tem]].index.values[0]

我还是更喜欢更简单的解决方案。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以通过将您描述的过滤和分配操作分成两个不同的步骤来做到这一点。

    Pandas 系列对象包含一个“isin”方法,可以让您识别其 column_1 值在 my_list 中的行,并将结果保存在布尔值系列中。这又可以与 .loc 索引方法一起使用,将相应行中的值从第 1 列复制到第 2 列

    # Identify the matching rows
    matches = df['column_1'].isin(my_list)
    # Set the column_2 entries to column_1 in the matching rows
    df.loc[matches,'column_2'] = df.loc[matches,'column_1']
    

    如果 column_2 尚不存在,此方法将创建 column_2 并将 non_matching 值设置为 NaN。 .loc 方法用于避免在执行索引操作时对数据的副本进行操作。

    【讨论】:

    • 我认为你不需要第二个 df.loc[...],所以它也可以这样工作:df.ix[(df['column_1'].isin(my_list)) , 'column_2'] = df['column_1'] 作为单列
    【解决方案2】:

    假设您有一个列表:

    l = ['foo', 'bar']
    

    和一个数据框:

    df = pd.DataFrame(['some', 'short', 'string', 'has', 'foo'], columns=['col1'])
    

    你可以使用df.apply

    df['col2'] = df.apply(lambda x: x['col1'] if x['col1'] in l else None, axis=1)
    
    df
        col1    col2
    0   some    None
    1   short   None
    2   string  None
    3   has     None
    4   foo     foo
    

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:

        试试这个单行:

        df.loc[(df['column_1'].isin(my_list)), 'column_2'] = df['column_1']
        

        与@res_edit 解决方案的不同之处在于缺少第二个df.loc[],它应该工作得更快...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-05
          • 1970-01-01
          • 2021-03-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多