簡體   English   中英

將單列拆分為 Dataframe 中的 4 個不同的列

[英]Split the single column to 4 different columns in Dataframe

我只需要將 dataframe 的一列拆分為 4 個不同的列。 我嘗試了幾個步驟但沒有奏效。

數據 1:

 Dump               
12525 2 153898 Winch
24798 1 147654 Gear
65116 4        Screw 
46456 1        Rowing
46563 5        Nut       

預期1:

 Item  Qty  Part_no  Description             
12525  2    153898   Winch
24798  1    147654   Gear
65116  4             Screw 
46456  1             Rowing
46563  5             Nut       

數據2:

 Dump               
12525 2 153898 Winch Gear
24798 1 147654 Gear nuts
65116 X        Screw bolts
46456 1        Rowing rings
46563 X        Nut       

預期2:

 Item  Qty  Part_no  Description             
12525  2    153898   Winch Gear
24798  1    147654   Gear nuts
65116  X             Screw bolts
46456  1             Rowing rings
46563  X             Nut       

我試過下面的代碼

data_df[['Item','Qty','Part_no','Description']] = data_df["Dump"].str.split(" ", 3, expand=True)

and got the output like 

 Item  Qty  Part_no  Description             
12525  2    153898   Winch
24798  1    147654   Gear
65116  4    Screw 
46456  1    Rowing
46563  5    Nut       

任何建議,我該如何解決???

使用str.extract

data_df[['Item','Qty','Part_no','Description']] = \
data_df['Dump'].str.extract(r'(\d+)\s+(\d+)\s+(\d*)\s*(\w+)')

Output:

                    Dump   Item Qty Part_no Description
0   12525 2 153898 Winch  12525   2  153898       Winch
1    24798 1 147654 Gear  24798   1  147654        Gear
2   65116 4        Screw  65116   4               Screw
3  46456 1        Rowing  46456   1              Rowing
4     46563 5        Nut  46563   5                 Nut

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM