[英]Python & Pandas: How to address NaN values in a loop?
使用 Python 和 Pandas,我試圖從 CSV 單元格中獲取值並通過循環將它們寫為 txt 文件。 CSV文件的結構是:
user_id, text, text_number
0, test text A, text_0
1,
2,
3,
4,
5, test text B, text_1
下面的腳本成功地為第一行寫入了一個 txt 文件 - 它被命名為 text_0.txt 並包含test text A
。
import pandas as pd
df= pd.read_csv("test.csv", sep=",")
for index in range(len(df)):
with open(df["text_number"][index] + '.txt', 'w') as output:
output.write(df["text"][index])
但是,當它繼續到下一行時,我收到一個錯誤:
TypeError: write() argument must be str, not float
我猜當它遇到讀取為NaN
值時會生成錯誤。 我嘗試根據dropna
文檔添加dropna
功能,如下所示:
import pandas as pd
df= pd.read_csv("test.csv", sep=",")
df2 = df.dropna(axis=0, how='any')
for index in range(len(df)):
with open(df2["text_number"][index] + '.txt', 'w') as output:
output.write(df2["text"][index])
但是,同樣的問題仍然存在 - 為第一行創建了一個 txt 文件,但為下一行返回了一條新的錯誤消息: KeyError: 1
。
有什么建議么? 非常感謝所有幫助。
這里的問題是您正在創建一個不一定在數據框索引中的范圍索引。 對於您的用例,您可以遍歷數據幀行並寫入文件。
for t in df.itertuples():
if t.text_number: # do not write if text number is None
with open(t.text_number + '.txt', 'w') as output:
output.write(str(t.text))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.