python - How do I select only some values in the column using pandas pivot table
问题描述
I want to make a pivot table, which will sort the column values and show the data.
I cannot able to select values in the columns
for example:
df = pd.read_excel("file1.xlsx")
inside this file
column name 1: cars : nissan, honda, hyundai, toyota, benz
column name 2: color: white, yellow, red, black, blue
column name 3: year: 2012, 2013, 2014, 2015, 2016
I want to make a pivot table as follows:
pd.pivot_table(df, index=['cars','color'], values='year', aggfunc='count', margins=True)
I want to create a pivot table which shows only nissan & honda in the cars column, and only white & black in the color column.
解决方案
loc
您可以使用基于这些值的数据透视表进行索引:
pivoted_df = pd.pivot_table(df, index=['cars','color'], values='year', aggfunc='count', margins=True)
pivoted_df.loc[(['honda', 'nissan'], ['white', 'black']), :]