python - Pandas 数据框 : How to parse integers into string of 0s and 1s?

标签 python regex parsing pandas

我有以下 pandas DataFrame。

import pandas as pd
df = pd.read_csv('filename.csv')

print(df)

      sample      column_A         
0     sample1        6/6    
1     sample2        0/4
2     sample3        2/6    
3     sample4       12/14   
4     sample5       15/21   
5     sample6       12/12   
..    ....

column_A 中的值不是分数,必须对这些数据进行处理,以便我可以将每个值转换为 0s1s (不要将整数转换成对应的二进制数)。

上面的“分子”给出了1的总数,而“分母”给出了01的总数.

因此,表格实际上应该采用以下格式:

      sample      column_A         
0     sample1     111111    
1     sample2     0000
2     sample3     110000    
3     sample4     11111111111100    
4     sample5     111111111111111000000 
5     sample6     111111111111  
..    ....

我从来没有像这样解析一个整数来输出 0 和 1 的字符串。如何做到这一点?是否有与 lambda 表达式一起使用的“pandas 方法”? Pythonic 字符串解析或正则表达式?

最佳答案

首先,假设你写了一个函数:

def to_binary(s):
    n_d = s.split('/')
    n, d = int(n_d[0]), int(n_d[1])
    return '1' * n + '0' * (d - n)

这样,

>>> to_binary('4/5')
'11110'

现在你只需要使用 pandas.Series.apply :

 df.column_A.apply(to_binary)

关于python - Pandas 数据框 : How to parse integers into string of 0s and 1s?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38571348/

相关文章:

Java将字符串拆分成段落

java - 以编程方式访问网页

python - Python 可以实现快速蜡烛图吗

Python(最新版本)语法错误

php - 正则表达式不返回任何与所使用的表达式无关的匹配项

parsing - 使用 flex/antlr 进行部分解析

parsing - 这些语法 : LL1, SLR1、LR0、LR1 和 LALR1 的层次结构是什么?

python - django 尾部斜杠基本 url

python - 变化计数程序的 if 语句中 undefined variable

regex - 我不明白正则表达式