使用Python将列拆分两次



我有一个像这样的大数据集(4GB(:

            userID   date   timeofday   seq
0   1000014754    20211028         20  133669542676:1:148;133658378700:1:16;133650937891:1:85
1   1000019906    20211028          6  508420199:0:0;133669581685:1:19
2   1000019906    20211028         22  133665269544:0:0 

由此,我想将";seq";通过"首先,使用重命名创建一个新的数据集。它看起来像这样:

            userID   date   timeofday   seq1      seq2  seq3 ... seqN
0   1000014754    20211028         20  133669542676:1:148 133658378700:1:16 133650937891:1:85
1   1000019906    20211028          6  508420199:0:0 133669581685:1:19 None None
2   1000019906    20211028         22  133665269544:0:0 None None None

然后我想拆分seq1,seq2,。。。,seqN通过":&";,并创建一个具有重命名的新数据集。它看起来像这样:

            userID   date   timeofday   name1  click1  time1 name2 click2 time2 ....nameN clickN timeN
0   1000014754    20211028         20  133669542676 1 148 133658378700 1 16 133650937891 1 85 None None None
1   1000019906    20211028          6  508420199 0 0 133669581685 1 19 None None None None None None
2   1000019906    20211028         22  133665269544 0 0 None None None None None None None None None

我知道pandas.split可以拆分列,但我不知道如何有效地拆分它。非常感谢。

一个干净的解决方案是使用正则表达式和extractall,然后使用unstack进行整形,将列和join重命名为原始数据帧。

假设df为数据帧名称

df2 = (df['seq'].str.extractall(r'(?P<name>[^:]+):(?P<click>[^:]+):(?P<time>[^;]+);?')
         .unstack('match')
         .sort_index(level=1, axis=1, sort_remaining=False)
       )
df2.columns = df2.columns.map(lambda x: f'{x[0]}{x[1]+1}')
df2 = df.drop(columns='seq').join(df2)

输出:

       userID      date  timeofday         name1 click1 time1         name2 click2 time2         name3 click3 time3
0  1000014754  20211028         20  133669542676      1   148  133658378700      1    16  133650937891      1    85
1  1000019906  20211028          6     508420199      0     0  133669581685      1    19           NaN    NaN   NaN
2  1000019906  20211028         22  133665269544      0     0           NaN    NaN   NaN           NaN    NaN   NaN

试试这个,它应该会得到结果:

A = pd.DataFrame({1:[2,3,4], 2:['as:d', 'asd', 'a:sd']})
print(A)
for i in A.index:
    split =str(A[2][i]).split(':',1)
    A.at[i,3] = split[0]
    if len(split) > 1:
        A.at[i, 4] = split[1]
print(A)

它可能很慢,因为数据帧经常更新。或者,您可以将新列写在单独的列表中,然后将它们合并到一个表中。2

最新更新