python - 正则表达式验证不适用于 Pandas 列中的大量数字
问题描述
我正在尝试验证数据框中特定正则表达式的列。数量限制为 (20,3),即 int 数据类型的最大长度为 20 或 float 数据类型的最大长度为 23。但是熊猫正在将原始数字转换为随机整数,而我的正则表达式验证失败了。我检查了我的正则表达式是否正确。
数据框:
FirstColumn,SecondColumn,ThirdColumn
111900987654123.123,111900987654123.123,111900987654123.123
111900987654123.12,111900987654123.12,111900987654123.12
111900987654123.1,111900987654123.1,111900987654123.1
111900987654123,111900987654123,111900987654123
111900987654123,-111900987654123,-111900987654123
-111900987654123.123,-111900987654123.123,-111900987654123.1
-111900987654123.12,-111900987654123.12,-111900987654123.12
-111900987654123.1,-111900987654123.1,-111900987654123.1
11119009876541231111,1111900987654123,1111900987654123
代码:
NumberValidationRegexnegative = r"^-?[0-9]{1,20}(?:\.[0-9]{1,3})?$"
df_CPCodeDF=pd.read_csv("D:\\FTP\LocalUser\\NCCLCOLL\\COLLATERALUPLOAD\\upld\\SplitFiles\\AACCR6675H_22102021_07_1 - Copy.csv")
pd.set_option('display.float_format', '{:.3f}'.format)
rslt_df2=df_CPCodeDF[df_CPCodeDF.iloc[:, 0].notna()]
rslt_df1=rslt_df2[~rslt_df2.iloc[:,0].apply(str).str.contains(NumberValidationRegexnegative, regex=True)].index
print("rslt_df1",rslt_df1)
输出结果:
rslt_df1 Int64Index([8], dtype='int64')
预期结果:
rslt_df1 Int64Index([], dtype='int64')
解决方案
用作dtype=str
的参数pd.read_csv
:
NumberValidationRegexnegative = r"^-?[0-9]{1,20}(?:\.[0-9]{1,3})?$"
df_CPCodeDF = pd.read_csv("data.csv", dtype=str)
rslt_df2 = df_CPCodeDF[df_CPCodeDF.iloc[:, 0].notna()]
rslt_df1 = rslt_df2[~rslt_df2.iloc[:,0] \
.str.contains(NumberValidationRegexnegative, regex=True)].index
输出:
>>> print("rslt_df1", rslt_df1)
rslt_df1 Int64Index([], dtype='int64')
推荐阅读
- spring-batch - SpringBatch:即使使用 NeverRetryPolicy,ChunkStep 也会在编写器中重试异常
- ssl - 如何让 Chrome/Firefox 提示我输入证书而不是默认为我以前使用的证书
- javascript - 尝试创建 Tampermonkey 用户脚本以等待视频期间弹出随机按钮并自动单击它
- r - shinyapp.io 应用程序的性能不如本地闪亮应用程序
- linux - 无法为 ARM 交叉编译 postgresql 12.2
- laravel - 当日期“from”和“to”为空时,Laravel 总是在我的报告中显示 01-Jan-1970 / 01-Jan-1970
- slack-api - Slack API 标记通道读取 2020
- powershell - 如果配置使用 configbuilders,我如何使用 powershell 获取网站的连接字符串?
- android-studio - 如何禁用非详尽的“何时”表达式检查?
- javascript - MongoDB:聚合查询匹配子文档数组的多个条件