Python & Pandas:如何在循环中处理 NaN 值?

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 的值时产生的。我尝试按 pandas documentation 添加 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))