【问题标题】:How to compare data from the same column in a dataframe (Pandas)如何比较数据框中同一列的数据(熊猫)
【发布时间】:2020-10-01 05:39:52
【问题描述】:

我有一个 Panda 的数据框,如下所示:

我想获得 2007 年 PIB 低于 2002 年的国家/地区,但我无法编写代码来仅使用 Pandas 内置方法而不使用 python 迭代或类似的东西来做到这一点。 我得到的最多的是以下行:

df[df[df.year == 2007].PIB < df[df.year == 2002].PIB].country

但我收到以下错误:

ValueError: Can only compare identically-labeled Series objects

到目前为止,我只使用 Pandas 过滤来自不同列的数据,但我不知道如何比较来自同一列的数据,在这种情况下是年份。 欢迎任何支持。

【问题讨论】:

  • 感谢您的所有回答,我是使用这些库的新手,我需要学习机器学习,非常感谢您的支持。并且只是为了将来可能有类似问题的用户的参考,对我有很大帮助的答案是标记的一个和这个:stackoverflow.com/a/64149984/11755598 因为解释了尝试比较的问题,就像我对我的代码所做的那样引发了ValueError 异常。
  • 我认为应该有一些数据相关的问题,是否可以共享数据或将它们发送到我的电子邮件?
  • 是的,我怎么联系你?
  • 你有!感谢您的支持。

标签: python pandas numpy dataframe


【解决方案1】:

我的策略是使用数据透视表。假设没有两行具有相同的 ('country','year') 对。在此假设下,aggfunc=np.sum 代表唯一的单个 PIB 值。

table = pd.pivot_table(df, values='PIB', index=['country'],
                    columns=['year'], aggfunc=np.sum)[[2002,2007]]
list(table[table[2002] > table[2007]].index)

pivot_table 如下所示:

【讨论】:

  • 你是对的。使用pivot 是更好的选择,不需要聚合。我将编辑我的答案:)
【解决方案2】:

我建议使用country 列的索引创建Series,但20072002 中的国家数量必须相同,以便比较具有相同索引值的系列:

df = pd.DataFrame({'country': ['Afganistan', 'Zimbabwe', 'Afganistan', 'Zimbabwe'],
                  'PIB': [200, 200, 100, 300], 
                  'year': [2002, 2002, 2007, 2007]})
print (df)
      country  PIB  year
0  Afganistan  200  2002
1    Zimbabwe  200  2002
2  Afganistan  100  2007
3    Zimbabwe  300  2007

df = df.set_index('country')
print (df)
            PIB  year
country              
Afganistan  200  2002
Zimbabwe    200  2002
Afganistan  100  2007
Zimbabwe    300  2007

s1 = df.loc[df.year == 2007, 'PIB'] 
s2 = df.loc[df.year == 2002, 'PIB']
print (s1)
country
Afganistan    100
Zimbabwe      300
Name: PIB, dtype: int64

print (s2)
country
Afganistan    200
Zimbabwe      200
Name: PIB, dtype: int64

countries = s1.index[s1 < s2]
print (countries)
Index(['Afganistan'], dtype='object', name='country')

另一个想法是首先以DataFrame.pivot 为中心,然后按年份查找列并与boolean indexing 中的索引进行比较:

df1 = df.pivot('country','year','PIB')
print (df1)
year        2002  2007
country               
Afganistan   200   100
Zimbabwe     200   300

countries = df1.index[df1[2007] < df1[2002]]
print (countries)
Index(['Afganistan'], dtype='object', name='country')

【讨论】:

    【解决方案3】:

    这是我的数据框:

    df = pd.DataFrame([
        {"country": "a", "PIB": 2, "year": 2002},
        {"country": "b", "PIB": 2, "year": 2002},
        {"country": "a", "PIB": 1, "year": 2007},
        {"country": "b", "PIB": 3, "year": 2007},
    ])
    

    如果我过滤 2002 年和 2007 年这两个年份,我得到了。

    df_2002 = df[df["year"] == 2007]
    out : 
      country  PIB  year
    0       a    2  2002
    1       b    2  2002
    
    df_2007 = df[df["year"] == 2007]
    out : 
      country  PIB  year
    2       a    1  2007
    3       b    3  2007
    

    您想比较每个国家/地区 PIB 的演变。

    Pandas 没有意识到这一点,它尝试比较值,但这里基于相同的索引。女巫不是你想要的,因为索引不同,所以不可能。

    所以你只需要使用set_index()

    df.set_index("country",  inplace=True)
    df_2002 = df[df["year"] == 2007]
    out : 
             PIB  year
    country           
    a          1  2007
    b          3  2007
    
    df_2007 = df[df["year"] == 2007]
    out : 
             PIB  year
    country           
    a          2  2002
    b          2  2002
    

    现在你可以进行比较了

    df_2002.PIB > df_2007.PIB
    out:
    country
    a     True
    b    False
    Name: PIB, dtype: bool
    
    # to get the list of countries
    (df_2002.PIB > df_2007.PIB)[res == True].index.values.tolist()
    out : 
    ['a']
    

    【讨论】:

      【解决方案4】:

      试试这个(考虑到您只需要这些国家的列表):

      [i for i in df.country if df[(df.country==i) & (df.year==2007)].PIB.iloc[0] < df[(df.country==i) & (df.year==2002)].PIB.iloc[0]]
      

      【讨论】:

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