在Pandas数据框架集上创建视图
很多时候,在做数据分析时,我们要处理的是一个有很多属性的大数据集。所有的属性不一定都同样重要。因此,我们希望只处理数据框架中的一组列。为此,让我们看看如何在数据框架上创建视图,只选择我们需要的那些列,而不考虑其他的。
给定一个包含nba数据的数据框架,在其上创建视图,使其只包括所需的列。
解决方案#1:当从csv文件中读取数据到Python时,我们可以选择所有我们想读入DataFrame的列。
# importing pandas as pd
import pandas as pd
# list of columns that we want to
# read into the DataFrame
use_cols =['Name', 'Number', 'College']
# Reading the csv file
df = pd.read_csv('nba.csv', usecols = lambda x : x in use_cols,
index_col = False)
# Print the dataframe
print(df)
输出 :

解决方案#2 :当从csv文件中读取数据到Python时,我们可以列出所有我们不想读入DataFrame的列。这就像丢弃那些列一样。
# importing pandas as pd
import pandas as pd
# list of columns that we do not want
# to read into the DataFrame
skip_cols =['Name', 'Number', 'College']
# Reading the csv file
df = pd.read_csv('nba.csv', usecols = lambda x : x not in skip_cols,
index_col = False)
# Print the dataframe
print(df)
输出 :

解决方案#3 :我们可以使用difference()方法来删除我们不需要的列。
# importing pandas as pd
import pandas as pd
# Reading the csv file
df = pd.read_csv("nba.csv")
# Print the dataframe
print(df)
输出 :

现在我们将通过使用difference()方法删除那些我们不需要的列。
# Drop the listed columns
df_view = df[df.columns.difference(['Position', 'Age', 'Salary'])]
# Print the new DataFrame
print(df_view)
输出 :

极客教程