Pandas Dataframe:如何将整数解析为0和1的字符串?

Sha*_*ang 4 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   
..    ....
Run Code Online (Sandbox Code Playgroud)

中的值column_A是不馏分,而这些数据必须被操纵,使得我可以每个值转换成0s1s(整数不转化成其二进制对应物).

上面的"分子"给出了总数1s,而"分母"给出了总数0s1s一起.

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

      sample      column_A         
0     sample1     111111    
1     sample2     0000
2     sample3     110000    
3     sample4     11111111111100    
4     sample5     111111111111111000000 
5     sample6     111111111111  
..    ....
Run Code Online (Sandbox Code Playgroud)

我从来没有解析过整数来输出像这样的0和1的字符串.怎么做到这一点?是否有与lambda表达式一起使用的"熊猫方法" ?Pythonic字符串解析还是正则表达式?

Ami*_*ory 6

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

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

以便,

>>> to_binary('4/5')
'11110'
Run Code Online (Sandbox Code Playgroud)

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

 df.column_A.apply(to_binary)
Run Code Online (Sandbox Code Playgroud)