【问题标题】:Python pandas data frame remove row where index name DOES NOT occurs in other data framePython pandas数据框删除索引名称不出现在其他数据框中的行
【发布时间】:2018-10-31 03:19:52
【问题描述】:

我有两个数据框。我想删除两个数据帧中都没有出现索引的行。

以下是数据框的示例:

import pandas as pd
data = {'Correlation': [1.000000, 0.607340, 0.348844]}

df = pd.DataFrame(data, columns=['Correlation'])
df = df.rename(index={0: 'GINI'})
df = df.rename(index={1: 'Central government debt, total (% of GDP)'})
df = df.rename(index={2: 'Grants and other revenue (% of revenue)'})

data_2 =  {'Correlation': [1.000000, 0.607340, 0.348844, 0.309390, -0.661046]}

df_2 = pd.DataFrame(data_2, columns=['Correlation'])
df_2 = df_2.rename(index={0: 'GINI'})
df_2 = df_2.rename(index={1: 'Central government debt, total (% of GDP)'})
df_2 = df_2.rename(index={2: 'Grants and other revenue (% of revenue)'})
df_2 = df_2.rename(index={3: 'Compensation of employees (% of expense)'})
df_2 = df_2.rename(index={4: 'Central government debt, total (current LCU)'})

我发现了这个问题:How to remove rows in a Pandas dataframe if the same row exists in another dataframe? 但无法使用它,因为如果索引名称相同,我试图删除它。

我也看到了这个问题:pandas get rows which are NOT in other dataframe,但删除了两个数据框中相等的行,但我也没有发现这很有用。

我想做的是转置然后连接数据框并删除重复的列:

df = df.T

df_2 = df_2.T

df3 = pd.concat([df,df_2],axis = 1)

df3.iloc[: , ~df3.columns.duplicated()]

这样做的问题是它只删除了重复的列之一,但我希望它删除这两列。

非常感谢您对此的任何帮助,干杯。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以只比较索引并使用.loc 拉取相关行:

    In [19]: df1 = pd.DataFrame(list(range(50)), index=range(0, 100, 2))
    
    In [20]: df2 = pd.DataFrame(list(range(34)), index=range(0, 100, 3))
    
    In [21]: df2.loc[df2.index.difference(df1.index)]
    Out[21]:
         0
    3    1
    9    3
    15   5
    21   7
    27   9
    33  11
    39  13
    45  15
    51  17
    57  19
    63  21
    69  23
    75  25
    81  27
    87  29
    93  31
    99  33
    

    【讨论】:

      【解决方案2】:

      您可以简单地对 df2 中的索引执行此操作,但不能在 df1 中执行此操作

      df_2[~df_2.index.isin(df.index)]
      
                                                    Correlation
      Compensation of employees (% of expense)         0.309390
      Central government debt, total (current LCU)    -0.661046
      

      【讨论】:

        【解决方案3】:

        我已经通过调整已经提交的答案来解决这个问题:

        df_2[df_2.index.isin(df.index)]
        

        【讨论】:

          猜你喜欢
          • 2022-11-05
          • 1970-01-01
          • 2016-06-01
          • 2021-12-30
          • 1970-01-01
          • 2021-07-08
          • 2015-12-26
          • 2018-05-22
          • 2021-07-22
          相关资源
          最近更新 更多