我正在尝试根据另一个列中是否包含字符串在pandas数据框中创建一个新列。我正在基于此post使用np.select。这是一个示例数据框和一个用于创建新列的示例函数
df=pd.DataFrame({'column':['one','ones','other','two','twos','others','three','threes']})
def add(df):
conditions = [
('one' in df['column']),
('two' in df['column']),
('three' in df['column']),
('other' in df['column'])]
choices = [1, 2, 3, 0]
df['Int'] = np.select(conditions, choices, default=0)
return df
new_df=add(df)
我得到的输出是
column Int
0 one 0
1 ones 0
2 other 0
3 two 0
4 twos 0
5 others 0
6 three 0
7 threes 0
我想要的是
column Int
0 one 1
1 ones 1
2 other 0
3 two 2
4 twos 2
5 others 0
6 three 3
7 threes 3
我在做什么错了?
答案 0 :(得分:1)
如果需要测试子字符串,请使用Series.str.contains
:
conditions = [
(df['column'].str.contains('one')),
(df['column'].str.contains('two')),
(df['column'].str.contains('three')),
(df['column'].str.contains('other'))]
如果需要完全匹配,请使用Series.eq
或==
:
conditions = [
(df['column'].eq('one')),
(df['column'].eq('two')),
(df['column'].eq('three')),
(df['column'].eq('other'))]
conditions = [
(df['column'] == 'one'),
(df['column'] == 'two'),
(df['column'] == 'three'),
(df['column'] == 'other')]
print (new_df)
column Int
0 one 1
1 ones 1
2 other 0
3 two 2
4 twos 2
5 others 0
6 three 3
7 threes 3