用这种数据读取csv

2024-04-26 07:49:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难读取这样的数据集:

#    title
#    description
#    link (could be not still active)
#    id
#    date
#    source (nyt|us|reuters)
#    category

示例:

court agrees to expedite n.f.l.'s appeal\n
the decision means a ruling could be made nearly two months before the regular season begins, time for the sides to work out a deal without delaying the 
season.\n
http://feeds1.nytimes.com/~r/nyt/rss/sports/~3/nbjo7ygxwpc/04nfl.html\n
0\n
04 May 2011 07:39:03\n
nyt\n
sport\n

我试过:

columns = ['title', 'description', 'link', 'id', 'date', 'source', 'category']
df = pd.read_csv('news', delimiter = "\n", names = columns,error_bad_lines=False)

但它把所有的信息都放进了标题栏。你知道吗

有人知道怎么处理吗?你知道吗

谢谢!你知道吗


Tags: columnstheto数据idsourcedatetitle
2条回答

以下是需要注意的几点:

1)任何长度超过1个字符的分隔符都由正则表达式解释。你知道吗

2)由于“c”引擎不支持regex,我将引擎显式定义为“python”,以避免出现警告。你知道吗

3)我必须添加一个伪列,因为文件末尾有一个“\n”,我后来使用drop删除了该列。你知道吗

所以,这些线有希望得到你想要的结果。你知道吗

columns = ['title', 'description', 'link', 'id', 'date', 'source', 'category','dummy']
df = pd.read_csv('news', names=columns, delimiter="\\\\n", engine='python').drop('dummy',axis=1)
df

我希望这有帮助:)

您不能使用\n作为csv的分隔符,您可以做的是将索引设置为等于列名,然后转置,即

df = pd.read_csv('news', index=columns).transpose()

相关问题 更多 >