我有以下数据。
df['íd'] = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O']
df['value'] = ['12','12','13','12','13','12','13','12','12','15','17','12','13','12','15']
如果相应的值等于12?
,如何将id作为新列单独获取答案 0 :(得分:1)
df = pd.DataFrame()
df['id'] = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O']
df['value'] = ['12','12','13','12','13','12','13','12','12','15','17','12','13','12','15']
df.loc[df['value'] == '12', 'new'] = df['id']
print (df)
id value new
0 A 12 A
1 B 12 B
2 C 13 NaN
3 D 12 D
4 E 13 NaN
5 F 12 F
6 G 13 NaN
7 H 12 H
8 I 12 I
9 J 15 NaN
10 K 17 NaN
11 L 12 L
12 M 13 NaN
13 N 12 N
14 O 15 NaN
df['new'] = df['id'].where(df['value'] == '12')
print (df)
id value new
0 A 12 A
1 B 12 B
2 C 13 NaN
3 D 12 D
4 E 13 NaN
5 F 12 F
6 G 13 NaN
7 H 12 H
8 I 12 I
9 J 15 NaN
10 K 17 NaN
11 L 12 L
12 M 13 NaN
13 N 12 N
14 O 15 NaN
编辑:
要与数字进行比较,请删除''
:
df = pd.DataFrame()
df['id'] = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O']
df['value'] = [12,12,13,12,13,12,13,12,12,15,17,12,13,12,15]
df.loc[df['value'] == 12, 'new'] = df['id']
print (df)
id value new
0 A 12 A
1 B 12 B
2 C 13 NaN
3 D 12 D
4 E 13 NaN
5 F 12 F
6 G 13 NaN
7 H 12 H
8 I 12 I
9 J 15 NaN
10 K 17 NaN
11 L 12 L
12 M 13 NaN
13 N 12 N
14 O 15 NaN
答案 1 :(得分:0)
以下是一些最简单的方法。
df['new'] = df[df.value == '12']['id']或左
df['new'] = df.query('value == "12"')['id']或
df['new'] = df['id'].where(df['value'] == '12')