Python Pandas 'Unnamed' 列不断出现

标签 python pandas dataframe

我遇到了一个问题,每次运行我的程序(从 .csv 文件读取数据帧)时,都会出现一个名为“未命名”的新列。

运行 3 次后的示例输出列 -

  Unnamed: 0  Unnamed: 0.1            Subreddit  Appearances

这是我的代码。对于每一行,“未命名”列仅增加 1。

df = pd.read_csv(Location)
while counter < 50:
    #gets just the subreddit name
    e = str(elem[counter].get_attribute("href"))
    e = e.replace("https://www.reddit.com/r/", "")
    e = e[:-1]
    if e in df['Subreddit'].values:
        #adds 1 to Appearances if the subreddit is already in the DF
        df.loc[df['Subreddit'] == e, 'Appearances'] += 1
    else:
        #adds new row with the subreddit name and sets the amount of appearances to 1.
        df = df.append({'Subreddit': e, 'Appearances': 1}, ignore_index=True)
    df.reset_index(inplace=True, drop=True)
    print(e)
    counter = counter + 2
#(doesn't work) df.drop(df.columns[df.columns.str.contains('Unnamed', case=False)], axis=1)

我第一次使用干净的 .csv 文件运行它时,它运行完美,但每次之后,都会出现另一个“未命名”列。 我只想每次都显示“Subreddit”和“外观”列。

最佳答案

另一种解决方案是读取具有属性 index_col=0 的 csv 以不考虑索引列:df = pd.read_csv(Location, index_col=0).

关于Python Pandas 'Unnamed' 列不断出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52730814/

相关文章:

python - Qt/QSql查询 : Binary data is interpreted as string when binding to BLOB field

Python 包构建 - 导入函数以在类定义中使用

python - 将三列之间的数学运算结果附加到下一行

python - 寻找在巨大的 Pandas Dataframe 中对一行进行切片的最快方法

python - 如何使用 python pandas 根据特定(字符串)列对数据框进行排序?

r - 从没有循环的数据帧列表中获取最大/最小值

python - Pandas OLS - 拉动参数不起作用

python - 如何遍历命令行上传递的所有文件行?

python - 将时间戳合并到自定义时间段中

python - 如果满足条件,则在数据框中填充一列