Python:如何从DataFrame提取含usa的账户及日期等指定内容
问题1:提取含usa的账户与日期
问题描述
第一个DataFrame的String1列包含如下文本:
| String1 |
|---|
| Table 671usa50452.tab has been created as of the process date (12-19-22). |
| Table 643usa50552.tab has been created as of the process date (12-19-22). |
| Table 681usa50532.tab has been created as of the process date (12-19-22). |
| Table 621usa56452.tab has been created as of the process date (12-19-22). |
| Table 547usa67452.tab has been created as of the process date (12-19-22). |
需要提取中间含usa的账户(如671usa50452)和日期(如12-19-22),生成包含原列、Account列、Date列的DataFrame。原代码未成功存入新列。
问题原因与解决方案
原代码存在两处问题:
- 列名错误:使用了
'String'而非实际列名'String1' - 正则不匹配:日期正则写为
\d{2}-\d{2}-\d{4}(四位年份),但目标日期是两位年份;同时未匹配账户后的.tab,导致提取失败。
正确代码
import pandas as pd # 构造示例DataFrame data1 = { 'String1': [ 'Table 671usa50452.tab has been created as of the process date (12-19-22).', 'Table 643usa50552.tab has been created as of the process date (12-19-22).', 'Table 681usa50532.tab has been created as of the process date (12-19-22).', 'Table 621usa56452.tab has been created as of the process date (12-19-22).', 'Table 547usa67452.tab has been created as of the process date (12-19-22).' ] } df_list1 = pd.DataFrame(data1) # 提取账户和日期 df_list1[['Account', 'Date']] = df_list1['String1'].str.extract(r'(\d+usa\d+)\.tab.*?\((\d{2}-\d{2}-\d{2})\)')
正则说明
(\d+usa\d+)\.tab:匹配数字+usa+数字的账户,同时匹配后续的.tab,确保提取准确.*?\((\d{2}-\d{2}-\d{2})\):匹配任意非贪婪字符后,提取括号内的两位年份日期
问题2:提取含usa的账户
问题描述
第二个DataFrame的String2列包含如下文本:
| String2 |
|---|
| 3203usa34088 : Asset USA1 / asd011245 |
| 3203usa34088 : Asset USA2 / ghf023345 |
| 3203usa34088 : Asset USA3 / hgf012735 |
| 3203usa34088 : Asset USA4 / wet012455 |
| 3203usa34088 : Asset USA5 / nbj012245 |
需要提取开头的含usa的账户(如3203usa34088),生成包含原列、Account2列的DataFrame。
解决方案
正确代码
import pandas as pd # 构造示例DataFrame data2 = { 'String2': [ '3203usa34088 : Asset USA1 / asd011245', '3203usa34088 : Asset USA2 / ghf023345', '3203usa34088 : Asset USA3 / hgf012735', '3203usa34088 : Asset USA4 / wet012455', '3203usa34088 : Asset USA5 / nbj012245' ] } df_list2 = pd.DataFrame(data2) # 提取账户 df_list2['Account2'] = df_list2['String2'].str.extract(r'^(\d+usa\d+)')
正则说明
^(\d+usa\d+):^匹配字符串开头,提取开头的数字+usa+数字的账户
内容的提问来源于stack exchange,提问作者exenlediatán
相关产品推荐
相关产品推荐

