簡體   English   中英

將一個系列拆分為多個 pandas 列

[英]split a series into multiple pandas columns

我有一個熊貓數據框,其中一列有一個系列。 結構如下:

Date          Col1
2022-01-02    'Amt_Mean                 2022.0\nAmt_Med                   5.0\nAmt_Std     877.0\ndtype: float64'


2022-01-03    'Amt_Mean                 2025.0\nAmt_Med                   75.0\nAmt_Std     27.0\ndtype: float64'

我想重塑它,以便得到以下輸出

Date        Amt_Mean   Amt_Med   Amt_Std
2022-01-02  2022.0     5.0       877.0
2022-01-03  2025.0     75.0      27.0

我怎樣才能做到這一點? 我嘗試了df['Col1'][0][1] ,它給了我第一個數量,我可以潛在地循環它,但似乎應該有一種更簡單(pythonic)的方式來做到這一點。 謝謝!

一些字符串處理將每個字符串轉換為字典,將它們轉換為數據幀,並將其與原始字符串連接:

new_df = pd.DataFrame([dict(re.split(r'\s+', y) for y in x.split('\n')[:-1]) for x in df['Col1']])
df = pd.concat([df.drop('Col1', axis=1), new_df], axis=1)

輸出:

>>> df
         Date Amt_Mean Amt_Med Amt_Std
0  2022-01-02   2022.0     5.0   877.0
1  2022-01-03   2025.0    75.0    27.0

假設您有pd.Series對象,我將使用鏈式pd.concat連接它們:

>>> pd.concat([df.Date, pd.concat([x for x in df.Col1], axis=1).T], axis=1)

         Date  Amt_Mean  Amt_Med  Amt_Std
0  2022-01-02      2022        5      877
1  2022-01-03      2025       75       27

這假設您的數據如下:

df = pd.DataFrame([{'Date':'2022-01-02', 
                    'Col1': pd.Series({'Amt_Mean': 2022, "Amt_Med": 5, "Amt_Std":877})}, 
                   {'Date':'2022-01-03', 
                    'Col1': pd.Series({'Amt_Mean': 2025, "Amt_Med": 75, "Amt_Std":27})
                   }])

暫無
暫無

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

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