在python中如何将一个数据帧的所有值连接成一个整数?

2024-09-28 23:21:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

           1  2  3  4  5  6  7  8  9  10
dog cat    1  1  0  1  1  1  0  0  1   0
    dog    1  1  1  1  1  1  0  0  1   1
    fox    1  1  1  1  1  1  0  0  1   1
    jumps  1  1  1  1  1  1  0  1  1   1
    over   1  1  1  1  1  1  0  0  1   1
    the    1  1  1  1  1  1  1  0  1   1

我想首先删除行和列中的所有标签,使df变成:

1  1  0  1  1  1  0  0  1   0
1  1  1  1  1  1  0  0  1   1
1  1  1  1  1  1  0  0  1   1
1  1  1  1  1  1  0  1  1   1
1  1  1  1  1  1  0  0  1   1
1  1  1  1  1  1  1  0  1   1

然后将这些值串联成一个长整数,这样它就变成:

110111001011111100111111110011111111011111111100111111111011

有没有人知道用最短的代码片段做这件事的方法。我很感激你的建议。非常感谢。你知道吗


Tags: the数据方法代码df整数标签建议
2条回答

IIUC公司

''.join(str(x) for x in sum(df.values.tolist(),[]))
Out[344]: '110111001011111100111111110011111111011111111100111111111011'

或者

''.join(map(str,sum(df.values.tolist(),[])))

选项1
apply(str.join)+str.cat

df.astype(str).apply(''.join, 1).str.cat(sep='')
'110111001011111100111111110011111111011111111100111111111011'

选项2
apply+np.add,文在寅提出:

np.sum(df.astype(str).apply(np.sum, 1))
'110111001011111100111111110011111111011111111100111111111011'

相关问题 更多 >