我正在使用pandas提取一个csv文件,仅提取一列,然后将其输出到文本文件。我的问题是,在输出时,它会在行号中添加一行。我需要该行号不存在。
到目前为止,我已经尝试了以下代码:(当/如果我可以使用此方法,则打印将替换为file.write(df)。
import pandas as pd
from pandas import DataFrame
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
file=open('BlockedIPs.txt', 'w')
df = pd.read_csv('IPOutput.csv', dtype='object')
df = df['IP Address (Impacted)'].astype('str')
#df = DataFrame(df) #I've commented these two lines out because they return "None"
#df = df.set_index('IP Address (Impacted)', inplace=True)
print(df)
实际输出为: …… 44036 185.176.27.18 44037 51.143.106.177 44038 51.143.106.177 44039 51.143.106.177 44040 173.194.152.170 44041 173.194.152.170 44042 173.194.152.170 44043 173.194.152.123 44044 173.194.152.123 44045 173.194.152.123
预期输出为:
185.176.27.18 51.143.106.177 51.143.106.177 51.143.106.177 173.194.152.170 173.194.152.170 173.194.152.170 173.194.152.123 173.194.152.123 173.194.152.123
答案 0 :(得分:0)
您所指的“行号”是数据框的索引。如果您未指定索引,Pandas会自动为您创建一个索引。 Pandas需要一个索引(某些行标识符),因此您可以将数据集的一列指定为该索引,可以创建一个新索引,也可以让Pandas进行(默认)。
如果要指定文件的一列作为索引,请指定参数index_col
的值,该值可以是单列或列列表。
请参阅文档here。
如果要输出不带索引的文件,只需将index
函数的to_csv
参数设置为False
(默认为True
)< / p>