保留以某些文本字符串开头的行

时间:2019-08-14 16:33:55

标签: python regex string pandas text

背景

我有以下df

import pandas as pd
df = pd.DataFrame({'Text' : ['\n[SPORTS FAN]\nHere', 
                                   'Nothing here', 
                                 '\n[BASEBALL]\nTHIS SOUNDS right',
                                 '\n[SPORTS FAN]\nLikes sports', 
                                   'Nothing is here', 
                                 '\n[NOT SPORTS]\nTHIS SOUNDS good',
                                 '\n[SPORTS FAN]\nReally Big big fan',
                                  '\n[BASEBALL]\nRARELY IS a fan'
                                ], 

                          'P_ID': [1,2,3,4,5,6,7,8], 
                          'P_Name' : ['J J SMITH', 
                                      'J J SMITH',
                                      'J J SMITH',
                                      'J J SMITH',
                                      'MARY HYDER', 
                                      'MARY HYDER', 
                                      'MARY HYDER', 
                                      'MARY HYDER']
                         })

输出

P_ID    P_Name      Text
0   1   J J SMITH   \n[SPORTS FAN]\nHere
1   2   J J SMITH   Nothing here
2   3   J J SMITH   \n[BASEBALL]\nTHIS SOUNDS right
3   4   J J SMITH   \n[SPORTS FAN]\nLikes sports
4   5   MARY HYDER  Nothing is here
5   6   MARY HYDER  \n[NOT SPORTS]\nTHIS SOUNDS good
6   7   MARY HYDER  \n[SPORTS FAN]\nReally Big big fan
7   8   MARY HYDER  \n[BASEBALL]\nRARELY IS a fan

目标

保留以'\n[SPORTS FAN]\\n[BASEBALL]\n开头的行

所需的输出

P_ID    P_Name      Text
0   1   J J SMITH   \n[SPORTS FAN]\nHere
2   3   J J SMITH   \n[BASEBALL]\nTHIS SOUNDS right
3   4   J J SMITH   \n[SPORTS FAN]\nLikes sports
6   7   MARY HYDER  \n[SPORTS FAN]\nReally Big big fan
7   8   MARY HYDER  \n[BASEBALL]\nRARELY IS a fan

问题

如何实现所需的输出?

1 个答案:

答案 0 :(得分:2)

尝试一下:

user_service = build('admin', 'directory_v1', credentials=d_creds)
user = user_service.users().get(userKey=userkey).execute()

if not user:
   print('user not found')
else:
   UserObj.fullName = user['name']['fullName']
   UserObj.lastLoginTime = user['lastLoginTime']
   UserObj.creationTime = user['creationTime']
   UserObj.deletionTime = user['deletionTime']
   UserObj.suspended = user['suspended']

不需要正则表达式