Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a data set that looks like this (see below). I want to create a new column that that holds the value 'NASA' when 'NASA' appears in the 1st column either by itself or as part of a larger string. How can I do this for a pandas data frame in python?

Thanks!

index selection
NASA- 16 51
NASA- 12 39
NASA- 8 38
NASA- 13 38
NASA- 9 34
NASA- 10 32
NASA- 15 30
NASA- 14 28
NASA- 17 27
NASA- 18 26
1990 NASA group 25
NASA- 11 23
NASA Astronaut Group 8 20
NASA- 5 19
NASA- 19 18
NASA-8 18
NASA-9 16
1978 NASA group 15
1996 NASA group 15
TsPK-8 15
NPOE-4 15
TsPK-2 14
question from:https://stackoverflow.com/questions/65943865/cleaning-categorical-data-with-pandas-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
172 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use np.where with str.contains to check whether your index column has 'NASA' in it. Note that you can use case=False to make the search case insensitive:

df['new_col'] = np.where(df['index'].str.contains('nasa',case=False),'NASA',"")

df
Out[11]: 
                     index  selection new_col
0                 NASA- 16         51    NASA
1                 NASA- 12         39    NASA
2                  NASA- 8         38    NASA
3                 NASA- 13         38    NASA
4                  NASA- 9         34    NASA
5                 NASA- 10         32    NASA
6                 NASA- 15         30    NASA
7                 NASA- 14         28    NASA
8                 NASA- 17         27    NASA
9                 NASA- 18         26    NASA
10         1990 NASA group         25    NASA
11                NASA- 11         23    NASA
12  NASA Astronaut Group 8         20    NASA
13                 NASA- 5         19    NASA
14                NASA- 19         18    NASA
15                  NASA-8         18    NASA
16                  NASA-9         16    NASA
17         1978 NASA group         15    NASA
18         1996 NASA group         15    NASA
19                  TsPK-8         15        
20                  NPOE-4         15        
21                  TsPK-2         14        

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...