如何使用包含需要拆分的字符串的行来操作pandas DataFrame

时间:2015-09-18 21:15:28

标签: python pandas

我有一个类似于表A的pandas数据框,我想获得表B.使用pandas最简单的方法是什么?

由于

表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

1 个答案:

答案 0 :(得分:0)

假设一个文件' tableA.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

Heres' data_aux':

   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