[英]Pandas: How to concat all cells of columns?
Given that i have the below dataset, which contains column with String
type.鉴于我有以下数据集,其中包含String
类型的列。
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: Ch3steR/Erfan 的回答适用于您所问的内容:
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:如果您希望索引为 C1、C2 等,您可以这样做:
cols_ = dt.columns
dt = dt.sum().reset_index(drop=True).to_frame(name = 'new_col_name')
dt.index = cols_
dt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.