37,721
社区成员
发帖
与我相关
我的任务
分享
import pandas as pd
#读取数据,更换列表名
data = pd.read_table( 'u.data' )
datafeilds = ['user id', 'item id', 'rating', 'timestamp']
data.columns = datafeilds
#将文件中需要的数据分别存入两个列表
user_id = []
gender = []
userfile = open('u.user')
contents = userfile.readlines()
userfile.close()
for i in range(0,len(contents)):
line = contents[i].split('|')
user_id.append( line[0] )
gender.append( line[2] )
#存入数据,为dataframe类型
dictuser = {'user id':user_id, 'gender':gender}
user = pd.DataFrame(dictuser)
rating = pd.merge( data, user, on = 'user id')
print rating
df = pd.DataFrame(data,columns=datafeilds)
运行到这就出错了
我在variable explorer看了data的值,显示只有1列,所以我自己用代码清理了一下。
data = np.loadtxt('u.data',delimiter = " ", dtype=str)
datafeilds = ['user id', 'item id', 'rating', 'timestamp']
sline = []
for line in data:
sline.append( line.split('\t') )
array = np.array(sline)
df = pd.DataFrame(array,columns=datafeilds)
最后,还是想请教一下,为何会出现题目中的问题呢?
两个数据都是<class 'pandas.core.frame.DataFrame'>
user id也都是<type 'str'>
到底哪里不一样呢?
再次感谢!print data.columns[0], user.columns[1]
print type(data.columns[0]), type(user.columns[1])
输出为
user id user id
<type 'str'> <type 'str'>
都是string啊
在variable explorer查看rating,有如下错误
TypeError: ufunc 'invert' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''#!/usr/bin/python
# -*- coding:utf-8 -*-
import pandas as pd
import numpy as np
#读取数据,更换列表名
data = np.loadtxt('u.data',delimiter = " ", dtype=str)
#data = pd.read_table( 'u.data' )
datafeilds = ['user id', 'item id', 'rating', 'timestamp']
#data.columns = datafeilds
df = pd.DataFrame(data,columns=datafeilds)
#将文件中需要的数据分别存入两个列表
user_id = []
gender = []
userfile = open('u.user')
contents = userfile.readlines()
userfile.close()
for i in range(0,len(contents)):
line = contents[i].split('|')
user_id.append( line[0] )
gender.append( line[2] )
#存入数据,为dataframe类型
dictuser = {'user id':user_id, 'gender':gender}
user = pd.DataFrame(dictuser)
rating = pd.merge( df, user, on = 'user id')
print rating
11 1 1 y1
22 2 2 y1
33 3 3 y1
44 4 4 y1
55 5 5 y1
66 6 6 y1
11|m|f
22|f|f
33|m|f
44|m|f
55|f|f
66|f|f