简体   繁体   English

动态在DataFrame中的Concat数字列

[英]Concat number columns in DataFrame dynamically

I want to concatenate DataFrame columns of numbers. 我想连接数字的DataFrame列。

First, to concat the numbers themselves I found this great solution here . 首先,为了确定数字本身,我在这里找到了一个很好的解决方案。

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

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

Now, I need to apply this to DataFrame columns. 现在,我需要将其应用于DataFrame列。 I can do so like this: 我可以这样:

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

But how can I do this with dynamic column names? 但是,如何使用动态列名呢? I don't want to have to manually write each column out separately. 我不想手动分别写出每一列。 Instead, I want to have a list of column names and somehow iterate through them to concat their contents. 相反,我想要一个列名列表,并以某种方式遍历它们以合并其内容。

(I'm not being lazy, just working with larger DataFrames). (我并不是很懒,只是使用更大的DataFrames)。

Thanks. 谢谢。

How about this? 这个怎么样? Concatenates all columns, rowwise: 按行连接所有列:

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

0    147
1    258
2    369
dtype: object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM