我有3列'Input_0','Input_1‘和'Input_2’。每个都包含二进制值。
如何将它们组合到包含组合输出的另一列,而不将它们转换为字符串,没有逗号等?
例如:
Input_0 Input_1 Input_2 Input
0 0 1 001
1 1 0 110
1 1 1 111
0 1 0 010 我试图转换成字符串,但因为我想在这些矩阵上做数学运算,因为类型不是numerical,所以它不起作用。
发布于 2021-06-09 04:38:18
这里有一种方法:
#!/usr/bin/env python
import io
import pandas as pd
table_str = '''Input_0, Input_1, Input_2
0, 0, 1
1, 1, 0
1, 1, 1
0, 1, 0
'''
def main():
df = pd.read_csv(io.StringIO(table_str), header=0, skipinitialspace=True)
df['Input'] = df[['Input_0', 'Input_1', 'Input_2']].astype(str).agg(''.join, axis=1)
print(df)
if __name__ == '__main__':
main()输出:
% ./67894205.py
Input_0 Input_1 Input_2 Input
0 0 0 1 001
1 1 1 0 110
2 1 1 1 111
3 0 1 0 010可以使用print(df.dtypes)来验证原始列是否保持为整数:
Input_0 int64
Input_1 int64
Input_2 int64
Input object
dtype: object如果这违反了您的问题参数,请澄清它们。
另一种选择可能是在列中使用apply,将字符串文字转换为字节文字,或通过bitstring库转换为位数组,例如:
#!/usr/bin/env python
import io
import pandas as pd
import bitstring
table_str = '''Input_0, Input_1, Input_2
0, 0, 1
1, 1, 0
1, 1, 1
0, 1, 0
'''
def main():
df = pd.read_csv(io.StringIO(table_str), header=0, skipinitialspace=True)
df['Input'] = df[['Input_0', 'Input_1', 'Input_2']].astype(str).agg(''.join, axis=1)
df['InputAsByte'] = df['Input'].apply(lambda x: bin(int(x, 2)))
df['InputAsBitArray'] = df['Input'].apply(lambda x: bitstring.BitArray(bin=x))
print(df)
print(df.dtypes)
if __name__ == '__main__':
main()下面的输出:
% ./67894205.modified.py
Input_0 Input_1 Input_2 Input InputAsByte InputAsBitArray
0 0 0 1 001 0b1 [False, False, True]
1 1 1 0 110 0b110 [True, True, False]
2 1 1 1 111 0b111 [True, True, True]
3 0 1 0 010 0b10 [False, True, False]
Input_0 int64
Input_1 int64
Input_2 int64
Input object
InputAsByte object
InputAsBitArray object一个好的答案可能取决于你想要做什么。
https://stackoverflow.com/questions/67894205
复制相似问题