新的python pandas dataframe列基于变量的值,使用函数

时间:2015-07-06 20:09:18

标签: python pandas dataframe

我有一个变量'<version>',范围从0到1600。我想根据“ImageName”的值创建一个新变量“LocationCode”。

如果“ImageName”小于70,我希望“ImageName”为1.如果“LocationCode”介于71和90之间,我想要'{{1} }'是2.我总共有13个不同的代码。我不知道如何在python pandas中写这个。这是我试过的:

ImageName

但它返回了一个错误。我显然没有以正确的方式定义事物,但我无法弄清楚如何。

2 个答案:

答案 0 :(得分:2)

你可以使用2个布尔掩码:

df.loc[df['ImageName'] <= 70, 'Test'] = 1
df.loc[(df['ImageName'] > 70) & (df['ImageName'] <= 90), 'Test'] = 2

通过使用掩码,您只需设置满足布尔条件的值,对于第二个掩码,您需要使用&运算符来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的方法。

答案 1 :(得分:0)

在Python中,您可以使用字典查找符号在一行中找到一个字段。字段名称为ImageName。在下面的spatLoc()函数中,参数行是包含整个行的字典,您可以使用字段名称作为字典的键来查找单独的列。

def spatLoc(row):
    if row['ImageName'] <=70:
        LocationCode = 1
    elif row['ImageName']  >70 and row['ImageName']  <=90:
        LocationCode = 2
    return LocationCode

df['test'] = df.apply(spatLoc, axis=1)
相关问题