gpt4 book ai didi

python - 尝试将字典转换为数据帧并使用 for 循环附加到同一数据帧

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:44 24 4
gpt4 key购买 nike

好吧,说实话,我不太确定如何问这个问题,因为我认为错误可能发生在多个地方,所以我将全部输入出来(感谢您对菜鸟的耐心这里)。

我正在尝试使用lastfm数据库: https://grouplens.org/datasets/hetrec-2011/

所以他们有这个Python脚本可以帮助我们从这个数据集中读取数据。

所以我所做的是,首先使用给定的 iter_lines 函数解析 csv 文件的行:

### first, open file into a file handle object
file = os.path.join(baseDir, 'artists.dat')
file_opener = open(file, "r")
lines = iter_lines(file_opener)

iter_lines() 函数如下所示(给定):

def iter_lines(open_file):
reader = csv.reader(
open_file,
delimiter='\t',
)
next(reader) # Skip the header
return reader

然后我尝试使用他们给定的parse_artist_line()函数来读取artist.csv:

artists_df = pd.DataFrame(['key','value'])

for line in lines:
### so the parse_artist_line() will return a dictionary
artist_dict = parse_artist_line(line)
artist_list = artist_dict.items()

### try to put in a temporary dataframe
temp = pd.DataFrame.from_dict(artist_dict, orient='index')

### finally append the temporary df to the artists_df
artists_df.append(temp, ignore_index=True)

print(artists_df.head(5))

当我使用最后一条语句打印 Artist_df 时,我只得到以下输出:

       0
0 key
1 value

他们的 parse_artist_line() 看起来像这样:

def parse_artist_line(line):
(artist_id, name, _, _) = line
current_artist = deepcopy(ARTISTS)
current_artist["artist_id"] = int(artist_id)
current_artist["name"] = name

return current_artist

顺便说一句,如果你打印 temp,它看起来像这样:

                     0
artist_id 18743
name Coptic Rain

如果我尝试使用“columns”作为 from_dict() 的“orient”参数输入,我会收到错误:

ValueError: If using all scalar values, you must pass an index

我关注了以下帖子/信息页面:

我不再确定我做错了什么(可能是每一步)。感谢任何帮助/指导!

最佳答案

我相信这里没有必要将文件转换为 dict 然后再转换为 DataFrame,更简单的是使用 read_csv如果需要过滤列名称,请添加参数 usecols:

artists_df = pd.read_csv('artists.dat', sep='\t', usecols=['id','name'])
print (artists_df.head())

id name
0 1 MALICE MIZER
1 2 Diary of Dreams
2 3 Carpathian Forest
3 4 Moi dix Mois
4 5 Bella Morte

如果想阅读所有列:

artists_df = pd.read_csv('artists.dat', sep='\t')
print (artists_df.head())

id name url \
0 1 MALICE MIZER http://www.last.fm/music/MALICE+MIZER
1 2 Diary of Dreams http://www.last.fm/music/Diary+of+Dreams
2 3 Carpathian Forest http://www.last.fm/music/Carpathian+Forest
3 4 Moi dix Mois http://www.last.fm/music/Moi+dix+Mois
4 5 Bella Morte http://www.last.fm/music/Bella+Morte

pictureURL
0 http://userserve-ak.last.fm/serve/252/10808.jpg
1 http://userserve-ak.last.fm/serve/252/3052066.jpg
2 http://userserve-ak.last.fm/serve/252/40222717...
3 http://userserve-ak.last.fm/serve/252/54697835...
4 http://userserve-ak.last.fm/serve/252/14789013...

关于python - 尝试将字典转换为数据帧并使用 for 循环附加到同一数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48515419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com