我有一个变量“ImageName
”,其范围为 0-1600。我想根据“ImageName
”的值创建一个新变量“LocationCode
”。
如果“ImageName
”小于 70,我希望“LocationCode
”为 1。如果“ImageName
”介于 71 和90,我希望 'LocationCode
' 为 2。我总共有 13 个不同的代码。我不知道如何在 python pandas 中编写这个。这是我尝试过的:
def spatLoc(ImageName):
if ImageName <=70:
LocationCode = 1
elif ImageName >70 and ImageName <=90:
LocationCode = 2
return LocationCode
df['test'] = df.apply(spatLoc(df['ImageName'])
但它返回了一个错误。显然我没有以正确的方式定义事物,但我不知道如何定义。
最佳答案
您可以只使用 2 个 bool 掩码:
df.loc[df['ImageName'] <= 70, 'Test'] = 1
df.loc[(df['ImageName'] > 70) & (df['ImageName'] <= 90), 'Test'] = 2
通过使用掩码,您只需设置满足 bool 条件的值,对于第二个掩码,您需要使用 &
运算符来 and
条件并括起来由于运算符优先级,括号中的条件
实际上我认为最好定义你的 bin 值并调用 cut
,例如:
In [20]:
df = pd.DataFrame({'ImageName': np.random.randint(0, 100, 20)})
df
Out[20]:
ImageName
0 48
1 78
2 5
3 4
4 9
5 81
6 49
7 11
8 57
9 17
10 92
11 30
12 74
13 62
14 83
15 21
16 97
17 11
18 34
19 78
In [22]:
df['group'] = pd.cut(df['ImageName'], range(0, 105, 10), right=False)
df
Out[22]:
ImageName group
0 48 [40, 50)
1 78 [70, 80)
2 5 [0, 10)
3 4 [0, 10)
4 9 [0, 10)
5 81 [80, 90)
6 49 [40, 50)
7 11 [10, 20)
8 57 [50, 60)
9 17 [10, 20)
10 92 [90, 100)
11 30 [30, 40)
12 74 [70, 80)
13 62 [60, 70)
14 83 [80, 90)
15 21 [20, 30)
16 97 [90, 100)
17 11 [10, 20)
18 34 [30, 40)
19 78 [70, 80)
这里的 bin 值是使用 range
生成的,但您可以自己传递 bin 值列表,一旦获得 bin 值,就可以定义查找字典:
In [32]:
d = dict(zip(df['group'].unique(), range(len(df['group'].unique()))))
d
Out[32]:
{'[0, 10)': 2,
'[10, 20)': 4,
'[20, 30)': 9,
'[30, 40)': 7,
'[40, 50)': 0,
'[50, 60)': 5,
'[60, 70)': 8,
'[70, 80)': 1,
'[80, 90)': 3,
'[90, 100)': 6}
您现在可以调用map
并添加新列:
In [33]:
df['test'] = df['group'].map(d)
df
Out[33]:
ImageName group test
0 48 [40, 50) 0
1 78 [70, 80) 1
2 5 [0, 10) 2
3 4 [0, 10) 2
4 9 [0, 10) 2
5 81 [80, 90) 3
6 49 [40, 50) 0
7 11 [10, 20) 4
8 57 [50, 60) 5
9 17 [10, 20) 4
10 92 [90, 100) 6
11 30 [30, 40) 7
12 74 [70, 80) 1
13 62 [60, 70) 8
14 83 [80, 90) 3
15 21 [20, 30) 9
16 97 [90, 100) 6
17 11 [10, 20) 4
18 34 [30, 40) 7
19 78 [70, 80) 1
可以修改上面的内容以满足您的需求,但这只是为了演示一种应该快速并且不需要迭代 df 的方法。
关于python - 基于变量值的新 python pandas 数据框列,使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31254714/