Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 熊猫按正则表达式选择列,并按if、else更改其值_Python 3.x_Regex_Pandas - Fatal编程技术网

Python 3.x 熊猫按正则表达式选择列,并按if、else更改其值

Python 3.x 熊猫按正则表达式选择列,并按if、else更改其值,python-3.x,regex,pandas,Python 3.x,Regex,Pandas,我有如下数据框: a b1 b2 b3 b4 c1 c2 c3 c4 a1 0.10 0.0 0.21 0.0 0.03 0.10 0.04 0.0 如何将其更改为以下内容: a b1 b2 b3 b4 c1 c2

我有如下数据框:

   a      b1         b2         b3       b4       c1      c2       c3         c4
   a1     0.10       0.0        0.21     0.0      0.03    0.10     0.04      0.0
如何将其更改为以下内容:

   a      b1         b2         b3       b4       c1      c2       c3         c4
   a1     1          0           1       0        1       0        1          0
所以,我想选择b*和c*列,并将任何非零值更改为1,将任何零值更改为0。所以,首先通过regex选择列,然后应用if-else规则。还值得注意的是,所有b*、c*列都是字符串obj类型


如何执行此操作?

不需要正则表达式,请改用str.startswith:

印刷品:

    a  b1  b2  b3  b4  c1  c2  c3  c4
0  a1   1   0   1   0   1   1   1   0
编辑:如果您的数字最初是字符串,则可以执行以下操作:

filter_col = [col for col in df if col.startswith('b') or col.startswith('c')]
df[filter_col] = (df[filter_col].astype(float) > 0).astype(int)
# if you want keep them as strings after computation:
# df[filter_col] = (df[filter_col].astype(float) > 0).astype(int).astype(str)
print(df)

不需要正则表达式,请改用str.startswith:

印刷品:

    a  b1  b2  b3  b4  c1  c2  c3  c4
0  a1   1   0   1   0   1   1   1   0
编辑:如果您的数字最初是字符串,则可以执行以下操作:

filter_col = [col for col in df if col.startswith('b') or col.startswith('c')]
df[filter_col] = (df[filter_col].astype(float) > 0).astype(int)
# if you want keep them as strings after computation:
# df[filter_col] = (df[filter_col].astype(float) > 0).astype(int).astype(str)
print(df)
另一个选项是str.match:

另一个选项是str.match:


您好@Andrej Kesley,我想将列的原始数据类型保留为字符串。@SumitSidana为什么要将数字存储为字符串?这里更广泛的上下文是什么?@SumitSidana您的意思是数字0和1应该是字符串而不是整数吗?@AndrejKeselyI get-TypeError:“>”在解决方案的“str”和“int”实例之间不受支持。值得注意的是,所有过滤器都是str类型。@SumitSidana我会在分析管道中尽可能长时间地将数字存储为数字,并将其转换为字符串作为最后一个stepHi@Andrej Kesley,我想将列的原始数据类型保留为字符串。@SumitSidana为什么要将数字存储为字符串?这里更广泛的上下文是什么?@SumitSidana您的意思是数字0和1应该是字符串而不是整数吗?@AndrejKeselyI get-TypeError:“>”在解决方案的“str”和“int”实例之间不受支持。值得注意的是,所有过滤器都是str类型。@SumitSidana我会在分析管道中尽可能长时间地将数字存储为数字,并在最后一步转换为字符串