简体   繁体   中英

Concat number columns in DataFrame dynamically

I want to concatenate DataFrame columns of numbers.

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. 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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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