如果列中有需要拆分的字符串行,如何操作DataFrame

2024-03-29 15:33:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似于表a的熊猫数据框,我想得到表B。使用熊猫最简单的方法是什么?你知道吗

谢谢

表A(ColofInt有不同长度的字符串要解析):

ColA ColB ColofInt             ColD 
A     B   StrA;StrB;StrC;       1
A     B   StrD;StrB;StrC;StrD;  3
A     B   StrC;StrB;            2
A     B   StrB;                 5

表B:

ColA ColB ColofInt1     ColofInt2 ColofInt2 ColofInt3  ColD 
A     B   StrA            StrB      StrC                1
A     B   StrD            StrB      StrC    StrD        3
A     B   StrC            StrB                          2
A     B   StrB                                          5

Tags: 数据方法字符串coldcolbcolastrastrb
1条回答
网友
1楼 · 发布于 2024-03-29 15:33:41

假设一个文件表格A.csv'包含以下内容:

ColA,ColB,ColofInt,ColD 
A,B,StrA;StrB;StrC;,1
A,B,StrD;StrB;StrC;StrD;,3
A,B,StrC;StrB;,2
A,B,StrB;,5

然后:

import pandas as pd
tableA= pd.read_csv('tableA.csv')

这将生成一个包含新列的数据帧

data_aux = pd.DataFrame(list(tableA.ColofInt.str.split(';').apply(lambda x: x[:-1])))
cols = []
for e in data_aux .columns:
    cols.append('ColofInt' + str(e+1)) 
data_aux .columns = cols

这是'数据':

   ColofInt1    ColofInt2   ColofInt3   ColofInt4
0   StrA        StrB        StrC        None
1   StrD        StrB        StrC        StrD
2   StrC        StrB        None        None
3   StrB        None        None        None

这将连接数据帧,删除原始列。你知道吗

tableB = pd.concat([tableA,data_aux],axis=1).drop('ColofInt',axis=1)

下面是结果“tableB”:

   ColA ColB    ColD    ColofInt1   ColofInt2   ColofInt3   ColofInt4
0   A   B       1       StrA        StrB        StrC        None
1   A   B       3       StrD        StrB        StrC        StrD
2   A   B       2       StrC        StrB        None        None
3   A   B       5       StrB        None        None        None

相关问题 更多 >