簡體   English   中英

如何在 Pandas 中將文本拆分為列而不收到“列必須與鍵長度相同”錯誤消息?

[英]How do I split text to columns in Pandas without getting "Columns must be same length as key" error message?

我嘗試基於“-”作為分隔符將一個 dataframe 列拆分為兩個,並且我得到一個 ValueError,顯示“列必須與鍵的長度相同”,即使在在線學習了多個教程之后也是如此。

The dataframe is named "epl_results_2015_22" and here are the dtypes of the dataframe: Wk float64 Day object Date datetime64[ns] Time object Home object Score object Away object dtype: object

這是 dataframe 的頭部的樣子:

Wk  Day Date    Time    Home    Score   Away
0   1.0 Fri 2021-08-13  20:00 (15:00)   Brentford   2–0 Arsenal
1   1.0 Sat 2021-08-14  12:30 (07:30)   Manchester Utd  5–1 Leeds United
2   1.0 Sat 2021-08-14  15:00 (10:00)   Leicester City  1–0 Wolves
3   1.0 Sat 2021-08-14  15:00 (10:00)   Burnley 1–2 Brighton
4   1.0 Sat 2021-08-14  15:00 (10:00)   Chelsea 3–0 Crystal Palace

我希望將“分數”列分成兩部分,“Home_Score”和“Away_Score”。 這是我嘗試運行的代碼:

epl_results_2015_22[['Home_Score','Away_Score']] = epl_results_2015_22.Score.str.split("-", expand=True)

拆分字符串應該是而不是-

df[["Home_Score", "Away_Score"]] = df["Score"].str.split("–", expand=True)
print(df)

印刷:

   Wk  Day            Date           Time            Home Score            Away Home_Score Away_Score
0   0  1.0  Fri 2021-08-13  20:00 (15:00)       Brentford   2–0         Arsenal          2          0
1   1  1.0  Sat 2021-08-14  12:30 (07:30)  Manchester Utd   5–1    Leeds United          5          1
2   2  1.0  Sat 2021-08-14  15:00 (10:00)  Leicester City   1–0          Wolves          1          0
3   3  1.0  Sat 2021-08-14  15:00 (10:00)         Burnley   1–2        Brighton          1          2
4   4  1.0  Sat 2021-08-14  15:00 (10:00)         Chelsea   3–0  Crystal Palace          3          0

暫無
暫無

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

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