index常用于to_sql等方法

index=True

输出显示index(索引)值

  1. dw_customer_order.to_sql('dw_customer_order_{}_2'.format(NAME), con=local,
  2. if_exists='replace', index=True)

image.png

index=False

输出不显示index(索引)值

  1. dw_customer_order.to_sql('dw_customer_order_{}_'.format(NAME), con=local,
  2. if_exists='replace', index=False)

image.png

as_index用于groupby

官方:as_index : boolean, default True For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output

  1. import pandas as pd
  2. df = pd.DataFrame(data={'books':['bk1','bk1','bk1','bk2','bk2','bk3'], 'price': [12,12,12,15,15,17],'num':[2,1,1,4,2,2]})
  3. print('df')

image.png

as_index=True

输出:

print(df.groupby('books',as_index=True).sum())

image.png

as_index=False

输出:

print(df.groupby('books',as_index=False).sum())

image.png
True时 自动把第一列作为了index
as_index为True时可以通过book的name来提取这本书的信息

df = df.groupby('books',as_index=True).sum()
print(df)
print('='*20)
print(df.loc['bk1'])

image.png