簡體   English   中英

使用 Pandas Dataframe,如何拆分特定列中的字符串,然后用拆分的第一個索引替換該字符串?

[英]Using a Pandas Dataframe, how can I split the strings in a specific column and then replace that string with the first index of the split?

我正在嘗試清理數據集的位置數據,並且某些位置有多個以逗號分隔的城市。 我想拆分逗號上有逗號的字符串,然后用拆分的第一個索引替換每個字符串。 (即;孟買、德里、加爾各答,然后讓它成為孟買)這是我寫的代碼,試圖做到這一點。 可以告訴我我做錯了什么嗎?

df_train = pd.read_csv("Final_Train_Dataset.csv", index_col= None)

for cell in df_train["location"]:
  new = df_train["location"].str.split(",")
df_train["new_location"] = new[0]
df_train["new_location"].head()

任何幫助深表感謝。 我不認為這很難弄清楚,但我是大熊貓的新手,我們正在將它用於課堂項目。

這將解決您的問題.split(expand=True)

df_train["new_location"] = df_train["location"].str.split(expand=True)[0]

暫無
暫無

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

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