简体   繁体   中英

Pandas: How to concat all cells of columns?

Given that i have the below dataset, which contains column with String type.

import numpy as np
import pandas as pd

dt = {
    "C1": ["A", "B", "B", "B", "A"],
    "C2": ["B", "A", "A", "B", "A"]
}

dt = pd.DataFrame(dt)

print(dt)

So, it looks like this

   C1  C2
0  A  B
1  B  A
2  B  A
3  B  B
4  A  A

I need to concate all the cells in each column and obtain a new dataset as below:

       C1
0  ABBBA
1  BAABA 

How can i do it?

Ch3steR/Erfan's answer works for what you've asked:

dt = dt.sum().reset_index(drop=True).to_frame(name=dt.columns[0])

If you want the index to be C1, C2 etc, you can just do this:

cols_ = dt.columns
dt = dt.sum().reset_index(drop=True).to_frame(name = 'new_col_name')
dt.index = cols_
dt

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