簡體   English   中英

如何將 output 從 for 循環寫入 dataframe pandas 中的列

[英]How to write output from a for loop to a column in a dataframe pandas

有人可以解釋如何將 for 循環的 output 寫入 dataframe 中的列嗎?

我在 dataframe 中有 3 條示例推文,其中包含 unicode 符號。 我想使用 for 循環刪除它們。

當我循環打印時,我得到了我想要的,但是當我嘗試將 output 寫入 dataframe 中的列時,什么也沒有發生。 我究竟做錯了什么?

for index, row in df.iterrows():
    row['content'] = row['content'].encode('ascii', 'ignore').decode()

你使用了錯誤的方法。 除了在一些非常罕見的情況下,您永遠不想循環 dataframe 行,主要是出於效率原因。

Pandas 具有為您完成工作的矢量化函數(例如“應用”)。

apply的工作原理是在特定 dataframe / 列的每個輸入上應用 function。

因此,在您的具體情況下,您想要做的是:


df['new_content'] = df.content.apply(lambda x: x.encode('ascii', 'ignore').decode()

暫無
暫無

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

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