在DataFrame數據表裏面提取須要的行

在DataFrame數據表裏面提取須要的行python

代碼功能:3d

 在DataFrame表格中使用loc(),獲得咱們想要的行,而後根據某一列元素的值進行排序blog

 此代碼中還展現了爲DataFrame添加列,即直接name_DataFrame['diff']=___便可,同時能夠依據新添加的列元素的值,來對dataframe進行排序排序

import pandas as pd


unames = ['user_id', 'gender', 'age','occupation','zip']
users = pd.read_table('users.dat', sep='::',header=None, names=unames)

rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table('ratings.dat', sep='::', header=None, names=rnames)

mnames = ['movie_id', 'title', 'genres']
movies = pd.read_table('movies.dat', sep='::', header=None, names=mnames)

data = pd.merge(pd.merge(ratings,users),movies)

mean_ratings = pd.pivot_table(data,index=['title'],values='rating',columns='gender')

print(mean_ratings[:10])

ratings_by_title = data.groupby('title').size()

print(ratings_by_title[:10])

active_titles = ratings_by_title.index[ratings_by_title >= 250]

print(active_titles)

active_mean_ratings = mean_ratings.loc[active_titles]

top_female_ratings = active_mean_ratings.sort_index(by='F', ascending=False)

active_mean_ratings['diff'] = active_mean_ratings['M'] - active_mean_ratings['F']

sorted_by_diff = active_mean_ratings.sort_index(by='diff')

print(sorted_by_diff[::-1][:15]) #注意對dataframe進行倒序訪問的方法

 

相關文章
相關標籤/搜索