繁体   English   中英

Python Pandas“未命名”列不断出现

[英]Python Pandas 'Unnamed' column keeps appearing

我遇到一个问题,每次我运行程序(从.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”和“ Appearances”列。

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

每次我运行程序(...)时,都会出现一个名为“未命名”的新列。

我想那是由于reset_index引起的,或者您的代码中某处有一个to_csv ,如@jpp建议的那样。 要修复to_csv确保使用index=False

df.to_csv(path, index=False)

通常,这是我将如何处理您的任务。 这样做是首先对所有外观进行计数(由e ),然后从这些计数中创建一个新的数据框,以与您已有的数据框合并( how='outer'添加尚不存在的行)。 这样避免了为每个元素重置索引,从而避免了该问题,并且性能更高。

以下是包含这些想法的代码:

base_df = pd.read_csv(location)
appearances = Counter()  # from collections
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]
    appearances[e] += 1
    counter = counter + 2
appearances_df = pd.DataFrame({'e': e, 'appearances': c } 
                               for e, c in x.items())
df = base_df.merge(appearances_df, how='outer', on='e')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM