gpt4 book ai didi

python - 基于正则表达式创建两个数据框

转载 作者:行者123 更新时间:2023-12-01 01:47:21 25 4
gpt4 key购买 nike

这是一个数据帧的小样本,我想将其拆分为两个单独的数据帧。

  No    Code         Name Rem Last Done   LACP     Chg  % Chg Vol ('00)  \
0 1 0012 3A [S] s 0.940 0.940 - - 20
1 2 7054 AASIA [S] s - 0.205 - - -
2 3 5238 AAX [S] s 0.345 0.340 0.005 +1.47 37,806
3 4 5238WA AAX-WA [S] s 0.135 0.135 - - 590
4 5 7086 ABLEGRP [S] s 0.095 0.100 -0.005 -5.00 300

我想根据匹配或不匹配以下 python 正则表达式来过滤“代码”列:

"^[0-9]{1,5}$"

最佳答案

使用str.containsboolean indexing , ~ 用于反转 bool 掩码:

m = df['Code'].str.contains("^[0-9]{1,5}$")

df1 = df[m]
print (df1)
No Code Name Rem Last Done LACP Chg % Chg Vol ('00)
0 1 0012 3A [S] s 0.940 0.940 - - 20
1 2 7054 AASIA [S] s - 0.205 - - -
2 3 5238 AAX [S] s 0.345 0.340 0.005 +1.47 37,806
4 5 7086 ABLEGRP [S] s 0.095 0.100 -0.005 -5.00 300

df2 = df[~m]
print (df2)
No Code Name Rem Last Done LACP Chg % Chg Vol ('00)
3 4 5238WA AAX-WA [S] s 0.135 0.135 - - 590

详细信息:

print (m)
0 True
1 True
2 True
3 False
4 True
Name: Code, dtype: bool

print (~m)
0 False
1 False
2 False
3 True
4 False
Name: Code, dtype: bool

关于python - 基于正则表达式创建两个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51129550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com