(Python)根据现有列的值创建新列

时间:2020-01-26 21:37:12

标签: python pandas numpy

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

此列是对我的数据中已经存在的“位置”列的修改。有7个唯一的位置,我想根据它们在我的数据集中出现<4次的条件来合并其中的3个位置。

假设我们有位置: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

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

3 个答案:

答案 0 :(得分:2)

如果您有一列位置:

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

答案 1 :(得分:1)

这是一种方法:

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

答案 2 :(得分:0)

您可以结合使用.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