我创建了以下 pandas 数据框:
ds = {'col1':[1,2,2,3,4,5,5,6,7,8]}
df = pd.DataFrame(data=ds)
数据框如下所示:
print(df)
col1
0 1
1 2
2 2
3 3
4 4
5 5
6 5
7 6
8 7
9 8
然后我创建了一个新字段,名为
newCol
,其定义如下:
def criteria(row):
if((row['col1'] > 0) & (row['col1'] <= 2)):
return "A"
elif((row['col1'] > 2) & (row['col1'] <= 3)):
return "B"
else:
return "C"
df['newCol'] = df.apply(criteria, axis=1)
新的数据框如下所示:
print(df)
col1 newCol
0 1 A
1 2 A
2 2 A
3 3 B
4 4 C
5 5 C
6 5 C
7 6 C
8 7 C
9 8 C
是否有可能创建这样的字典:
dict = {
'0 <= 2' : "A",
'2 <= 3' : "B",
'Else' : "C"
}
然后将其应用到数据框:
df['newCol'] = df['col1'].map(dict)
?
有人可以帮助我吗?
IntervalIndex
来做到这一点:
dic = {(0, 2): 'A',
(2, 3): 'B',
}
other = 'C'
bins = pd.IntervalIndex.from_tuples(dic)
labels = list(dic.values())
df['newCol'] = (pd.Series(labels, index=bins)
.reindex(df['col1']).fillna(other)
.tolist()
)
但是考虑到你的例子,使用
cut
似乎更直接:
df['newCol'] = pd.cut(df['col1'], bins=[0, 2, 3, np.inf], labels=['A', 'B', 'C'])
输出:
col1 newCol
0 1 A
1 2 A
2 2 A
3 3 B
4 4 C
5 5 C
6 5 C
7 6 C
8 7 C
9 8 C