【问题标题】:Remove columns from data frame with hashing使用散列从数据框中删除列
【发布时间】:2017-02-13 18:09:19
【问题描述】:

给定两个 pandas 数据框:

df1 = pd.read_csv(file1, names=['col1','col2','col3'])
df2 = pd.read_csv(file2, names=['col1','col2','col3'])

我想删除 df2 中 col1col2(或两者)的值在 df1 中不存在的所有行。

执行以下操作:

df2 = df2[(df2['col1'] in set(df1['col1'])) & (df2['col2'] in set(df1['col2']))]

产量:

TypeError: 'Series' 对象是可变的,因此它们不能被散列

【问题讨论】:

    标签: python pandas indexing merge multiple-columns


    【解决方案1】:

    我觉得你可以试试isin:

    df2 = df2[(df2['col1'].isin(df1['col1'])) & (df2['col2'].isin(df1['col2']))]
    
    df1 = pd.DataFrame({'col1':[1,2,3,3],
                        'col2':[4,5,6,2],
                        'col3':[7,8,9,5]})
    
    print (df1)
       col1  col2  col3
    0     1     4     7
    1     2     5     8
    2     3     6     9
    3     3     2     5
    
    df2 = pd.DataFrame({'col1':[1,2,3,5],
                        'col2':[4,7,4,1],
                        'col3':[7,8,9,1]})
    
    print (df2)
       col1  col2  col3
    0     1     4     7
    1     2     7     8
    2     3     4     9
    3     5     1     1
    
    df2 = df2[(df2['col1'].isin(df1['col1'])) & (df2['col2'].isin(df1['col2'].unique()))]
    print (df2)
       col1  col2  col3
    0     1     4     7
    2     3     4     9
    

    另一种解决方案是merge,因为默认情况下是内连接 (how='inner'),但它仅适用于在两个 DataFrames 中具有相同位置的值:

    print (pd.merge(df1, df2))
       col1  col2  col3
    0     1     4     7
    

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 1970-01-01
      • 2017-03-16
      • 2017-10-28
      • 2019-05-18
      • 1970-01-01
      • 2021-09-29
      • 2021-01-07
      • 2012-11-13
      相关资源
      最近更新 更多