【问题标题】:Subtract strings from columns and keep original index in Pandas从列中减去字符串并在 Pandas 中保留原始索引
【发布时间】:2020-09-11 21:54:14
【问题描述】:

我有一个包含两列的 df:

country      amount
USA          34 
USA          21
China        5
France       7
Italy        9
USA          1
Spain        10
Ireland      12

我想根据大洲创建 3 个变量:美国、中国和欧洲,以便使用“金额”列进行进一步计算。

对于美国和中国,我是这样做的:

    usa = df.loc[df['country']=='USA']['country']
    china = df.loc[df['country']=='China (Mainland)']['country']

对于欧洲,我陷入了困境,因为我需要列中的所有欧洲国家并维护其索引(因此相应的数量)。

是否可以从 ['country'] usa 和 china 中减去,得到其余的(欧洲国家)并将它们存储在变量 'europe' 中?

例如,最终目标是获得所有欧洲国家的数量之和,不幸的是,没有另一个“标记”可以将它们区分为欧洲国家。

【问题讨论】:

    标签: python pandas selection


    【解决方案1】:

    您可以获得所有不是USAChina 的国家/地区。

    为此,您可以使用以下方法

    europe = df.loc[(df['country']!='China (Mainland)') & (df['country']!='USA')]['country']
    

    【讨论】:

      【解决方案2】:

      检查

      EU = df.loc[~df['country'].isin(['USA', 'China (Mainland)'])]['country']
      

      【讨论】:

      • ~df['country'] 中的 ~ 是什么?谢谢
      • @Steven in to not in ~
      【解决方案3】:

      美国和中国不是大陆:)

      df['continent'] = 'Europe'
      df['continent'][df['country']=='USA'] = 'USA'
      df['continent'][df['country']=='China'] = 'China (Mainland)'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-21
        • 1970-01-01
        • 2022-01-03
        • 1970-01-01
        • 2019-07-13
        • 2023-03-21
        • 2012-11-14
        • 2019-01-06
        相关资源
        最近更新 更多