我有一個像這樣的大資料集(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 可以拆分列,但我不知道如何有效拆分它。謝謝!
uj5u.com熱心網友回復:
一個干凈的解決方案是使用正則運算式 and extractall,然后使用 reshape 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
uj5u.com熱心網友回復:
試試這個,它應該給你結果:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/399874.html
