我有以下 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
中的值不是分数,必须对这些数据进行处理,以便我可以将每个值转换为 0s
和 1s
(不要将整数转换成对应的二进制数)。
上面的“分子”给出了1
的总数,而“分母”给出了0
和1
的总数.
因此,表格实际上应该采用以下格式:
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/