我遇到了一个问题,每次运行我的程序(从 .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/