【问题标题】:(Python) Create New Column Based on Values of Existing Column(Python) 根据现有列的值创建新列
【发布时间】:2020-01-27 06:08:50
【问题描述】:

我有一个 116 行和 43 列的数据集。我想从我的 Python 数据集中的现有列创建一个新列。

此列将是对我的数据中已存在的“位置”列的修改。有 7 个独特的位置,我想根据它们在我的数据集中出现

假设我们有位置:A、B、C、D、E、F 和 G。这些位置在我的数据集中出现的次数如下。

Location     NumRows
A            41
B            30
C            28
D            8
E            3
F            3
G            2

根据我上面的描述,我希望新列(位置 2)具有以下行数:

Location     NumRows
A            41
B            30
C            28
D            8
Other        8

有人可以帮助我了解创建此新列的语法吗?任何帮助将不胜感激!

【问题讨论】:

  • 我猜这是 Pandas DataFrame?你读过 Pandas 文档吗?
  • 另外,我相信您给出的示例并不能准确传达/代表您给出的条件,即 有 7 个独特的位置,我想根据条件是它们在我的数据集中出现

标签: python pandas numpy


【解决方案1】:

如果您有一列位置:

print(df)                                                               
   ID Location
0   1        A
1   2        B
2   3        A
3   4        C
4   5        E
5   6        F
6   7        G
7   8        D
8   9        D
9  10        B

你可以使用Series.isin:

df['NewLocation'] = df['Location']
df.loc[df['NewLocation'].isin(['E','F','G']), 'NewLocation'] = 'Other'

print(df)                                                              
   ID Location NewLocation
0   1        A           A
1   2        B           B
2   3        A           A
3   4        C           C
4   5        E       Other
5   6        F       Other
6   7        G       Other
7   8        D           D
8   9        D           D
9  10        B           B

【讨论】:

    【解决方案2】:

    这是一种方法:

    locs = ['E','F','G']
    
    # calculate value
    v = df.query("Location in @locs")['NumRows'].sum()
    
    # create a new row
    r = pd.Series(['Other', v], index=['Location','NumRows'])
    
    # append the new row in data
    df = df.query("Location not in @locs").append(r, ignore_index=True)
    
      Location  NumRows
    0        A       41
    1        B       30
    2        C       28
    3        D        8
    4    Other        8
    

    【讨论】:

      【解决方案3】:

      你可以结合.groupby()np.where()

      df = df.groupby(
              np.where(df['Location'].isin(['E', 'F', 'G']), 'Other', df.Location)
          ).sum().reset_index().rename(columns={'index':'Location'})
      

        Location  NumRows
      0        A       41
      1        B       30
      2        C       28
      3        D        8
      4    Other        8
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-19
        • 1970-01-01
        • 2018-10-07
        • 1970-01-01
        • 2020-01-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多