动态连接 DataFrame 中的数字列

Concat number columns in DataFrame dynamically

我想连接 DataFrame 的数字列。

首先,为了连接数字本身,我找到了这个很好的解决方案 here

In [1]: l = [1,2,3,4]

In [2]: int(''.join(map(str,l)))
Out[2]: 1234

现在,我需要将其应用于 DataFrame 列。我可以这样做:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]})

In [3]: df
Out[3]: 
   a  b  c
0  1  4  7
1  2  5  8
2  3  6  9

In [4]: df['concat'] = df['a'].astype(str) + df['b'].astype(str) + df['c'].astype(str)

In [5]: df
Out[5]: 
   a  b  c concat
0  1  4  7    147
1  2  5  8    258
2  3  6  9    369

但是我如何使用动态列名来做到这一点?我不想单独手动写出每一列。相反,我想要一个列名列表,并以某种方式遍历它们以连接它们的内容。

(我不是懒惰,只是使用更大的 DataFrame)。

谢谢。

这个怎么样?按行连接所有列:

df.apply(lambda x: ''.join(map(str,x)),axis=1)

0    147
1    258
2    369
dtype: object