简体   繁体   中英

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

I tried splitting one dataframe column into two based on "-" as a delimiter, and I'm getting a ValueError that reads "Columns must be same length as key," even after following multiple tutorials online.

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

And here is what the head of the dataframe looks like:

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

I want the "Score" column to be split into two, "Home_Score" and "Away_Score." Here is the code I tried to run:

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

The splitting string should be not - :

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

Prints:

   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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM