[英]duplicating rows by splitting comma separated multiple values in another column pandas
我找到了應該在NameError 中工作的代碼:未定義名稱“系列”
但我收到一個錯誤“名稱'系列'未定義”。 它在示例中運行良好,但其他用戶也出現了此錯誤。 有誰知道如何使它工作?
任何幫助,將不勝感激!
original_df = DataFrame([{'country': 'a', 'title': 'title1'},
{'country': 'a,b,c', 'title': 'title2'},
{'country': 'd,e,f', 'title': 'title3'},
{'country': 'e', 'title': 'title4'}])
desired_df = DataFrame([{'country': 'a', 'title': 'title1'},
{'country': 'a', 'title': 'title2'},
{'country': 'b', 'title': 'title2'},
{'country': 'c', 'title': 'title2'},
{'country': 'd', 'title': 'title3'},
{'country': 'e', 'title': 'title3'},
{'country': 'f', 'title': 'title3'},
{'country': 'e', 'title': 'title4'}])
#Code I used:
desired_df = pd.concat(
[
Series(row["title"], row["country"].split(","))
for _, row in original_df.iterrows()
]
).reset_index()
首先用逗號split
列以獲取列表,然后您可以explode
該系列列表。 將'title'
移動到索引中,以便為'country'
中的每個元素重復它。 最后兩部分只是清理名稱並從索引中刪除標題。
(df.set_index('title')['country']
.str.split(',')
.explode()
.rename('country')
.reset_index())
title country
0 title1 a
1 title2 a
2 title2 b
3 title2 c
4 title3 d
5 title3 e
6 title3 f
7 title4 e
此外,您的原始代碼在邏輯上沒有問題,但您需要正確創建 object。 我建議導入模塊而不是單個類/方法,因此您使用pd.Series
而不是Series
創建一個Series
import pandas as pd
desired_df = pd.concat([pd.Series(row['title'], row['country'].split(','))
for _, row in original_df.iterrows()]).reset_index()
您可以在此處將pd.Series.str.split
與df.explode
一起使用。
df['country'] = df['country'].str.split(',')
df.explode('country').reset_index(drop=True)
country title
0 a title1
1 a title2
2 b title2
3 c title2
4 d title3
5 e title3
6 f title3
7 e title4
對於NameError
,您可以通過這種方式使用 import。
from pandas import DataFrame, Series
注意:使用上述導入語句只會將DataFrame
和Series
類帶入 scope。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.