在Pandas DataFrame上创建视图
很多时候,在做数据分析时,我们要处理一个大的数据集,有很多属性。所有的属性不一定同样重要。因此,我们希望只处理数据框架中的一组列。为此,让我们看看如何在数据框架上创建视图,只选择我们需要的那些列,而不考虑其他的。
解决方案#1:可以通过删除所有不需要的列来选择DataFrame中的一组列。
# importing pandas as pd
import pandas as pd
# Reading the csv file
df = pd.read_csv("nba.csv")
# Print the dataframe
print(df)
输出 :
现在我们将选择除前三列以外的所有列。
# drop the first three columns
df.drop(df.columns[[0, 1, 2]], axis = 1)
输出 :
我们也可以使用要删除的列的名称。
# drop the 'Name', 'Team' and 'Number' columns
df.drop(['Name', 'Team', 'Number'], axis = 1)
输出 :
解决方案#2 :我们可以单独选择所有我们需要的列,而忽略其他的。
# importing pandas as pd
import pandas as pd
# Reading the csv file
df = pd.read_csv("nba.csv")
# select the first three columns
# and store the result in a new dataframe
df_copy = df.iloc[:, 0:3]
# Print the new DataFrame
df_copy
输出 :
我们也可以通过向DataFrame.iloc属性传递一个列表,以随机方式选择列。
# select the first, third and sixth columns
# and store the result in a new dataframe
# The numbering of columns begins from 0
df_copy = df.iloc[:, [0, 2, 5]]
# Print the new DataFrame
df_copy
输出 :
另外,我们也可以为我们想要选择的列命名。
# Select the below listed columns
df_copy = df[['Name', 'Number', 'College']]
# Print the new DataFrame
df_copy
输出 :