[英]Convert column with more than one string into rows with Pandas
我正在從 Google 表格中收集一些數據,但我需要將包含多個字符串的一列轉換為一行。 每個單元格可以有多個字符串,每個字符串我想放在一行
我有這個 dataframe
import pandas as pd
df = pd.DataFrame({'Name': ['Bob', 'John', 'Ric'],
'Submitted At': ['2022/08/12 23:56:42', '2022/08/12 23:56:42', '2022/08/12 23:56:42'],
'Class': ['Math,English,History', 'English,History', 'Math, Chemistry']})
print(df)
Name Submitted At Class
0 Bob 2022/08/12 23:56:42 Math,English,History
1 John 2022/08/12 23:56:42 English,History
2 Ric 2022/08/12 23:56:42 Math, Chemistry
我想把它變成這個
我正在嘗試這樣做,但沒有奏效
df2 = df.join(df['Class'].str.split(',', expand=True).add_prefix('Class'))
print(df2.melt(id_vars=['Submitted At', 'Name'], var_name=df2.iloc[:, 2:6]))
ValueError:無法強制轉換為系列,長度必須為 4:給定 2
請問你能幫幫我嗎?
你可以試試explode
拆分列表Class
列
out = (df.assign(Class=df['Class'].str.split(','))
.explode('Class', ignore_index=True))
print(out)
Name Submitted At Class
0 Bob 2022/08/12 23:56:42 Math
1 Bob 2022/08/12 23:56:42 English
2 Bob 2022/08/12 23:56:42 History
3 John 2022/08/12 23:56:42 English
4 John 2022/08/12 23:56:42 History
5 Ric 2022/08/12 23:56:42 Math
6 Ric 2022/08/12 23:56:42 Chemistry
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.