我正在尝试编写一个Python代码来训练一个数据集,以识别一个新闻项是假的还是真的。我需要能够将数据放入列中,即属性和目标。“is sarcastic”列是目标,该列的值为1或0。“标题”和“文章链接”列是属性。数据集非常庞大,由数千行组成。下面我只展示了其中的三行。我的问题是:给定一个原始的JSON文件,我把它转换成一个CSV文件,可以在Excel中读取。但是当我用Python显示数据时,属性并没有分开,而是集中在一列中,我不知道如何将它们分开。下面是我的代码的一部分(我没有列出我所有的导入或学习):
import pandas as pd
from pandas import DataFrame
from sklearn.model_selection import train_test_split
file1 = pd.read_csv(r"C:\Users\JohnBoy\Downloads\fake.csv", sep='delimiter', header=None, engine='python')
file2 = pd.DataFrame(file1)
print(file2)
file2.shape
file2.head()
file2.columns.values
Now, below is the raw JSON file which I later converted to CSV:
{"is_sarcastic": 1, "headline": "thirtysomething scientists unveil doomsday clock of hair loss", "article_link": "https://www.theonion.com/thirtysomething-scientists-unveil-doomsday-clock-of-hai-1819586205"}
{"is_sarcastic": 0, "headline": "dem rep. totally nails why congress is falling short on gender, racial equality", "article_link": "https://www.huffingtonpost.com/entry/donna-edwards-inequality_us_57455f7fe4b055bb1170b207"}
{"is_sarcastic": 0, "headline": "eat your veggies: 9 deliciously different recipes", "article_link": "https://www.huffingtonpost.com/entry/eat-your-veggies-9-delici_b_8899742.html"}
下面是我运行上面的Python代码时在Jupyter笔记本中看到的内容(这里只显示了三行):
0
0 "is_sarcastic","headline","article_link"
1 1,"thirtysomething scientists unveil doomsday ...
2 0,"dem rep. totally nails why congress is fall...
3 0,"eat your veggies: 9 deliciously different r...
**[11205 rows x 1 columns]**
array([0], dtype=int64)
键入时:
df1.headline
df1.head()
我得到错误消息:“DataFrame”对象没有“headline”属性。这显然意味着,我没有3列,而是只有一列(您可以清楚地看到,它是11205行x1列)。我做错什么了?我好像不能把我的专栏分开。你知道吗
pandas模块的方法
read_csv()
返回DataFrame对象。所以构造file2 = pd.DataFrame(file1)
的行是完全没有必要的。你知道吗第二,打开
.csv
文件时,需要指定分隔符/分隔符arg:sep
(一种将数据划分为行中的列的字符),该字符在file1
构造中的指定不正确。你知道吗因为您指定在Excel中打开时可以看到逗号,所以在您的案例中分隔符是逗号。你知道吗
你把
header
设为无。如果在csv的第一行中有标题,那么它应该是0(行的索引)。你知道吗所以你的代码应该是,
file1 = pd.read_csv(r"C:\Users\JohnBoy\Downloads\fake.csv", sep=',', header=0, engine='python')
第三,在Excel中打开csv文件时,打开一张空白页,然后转到“数据”>;“选择从文本数据导入”>;“选择csv文件”。然后您将看到用于处理数据的分隔符选项。选择逗号后,您将能够在Excel中正确查看。你知道吗
相关问题 更多 >
编程相关推荐