pandas.DataFrame.reset_index
reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')
1)函数作用:
2)参数:
3)返回
import pandas as pd
import numpy as np
df = pd.DataFrame([('bird', 389.0), ('bird', 24.0), ('mammal', 80.5), ('mammal', np.nan)],
index=['falcon', 'parrot', 'lion', 'monkey'], columns=('class', 'max_speed'))
print(df)
print('\n')
df1 = df.reset_index()
print(df1)
print('\n')
df2 = df.reset_index(drop=True)
print(df2)
import pandas as pd
import numpy as np
df = pd.DataFrame([('bird', 389.0), ('bird', 24.0), ('mammal', 80.5), ('mammal', np.nan)],
index=['falcon', 'parrot', 'lion', 'monkey'], columns=('class', 'max_speed'))
print(df)
print('\n')
df1 = df.reset_index()
print(df1)
print('\n')
df2 = df.reset_index(inplace=True)
print(df2)
print('\n')
print(df)
如果索引有多个列,仅从索引中删除由level指定的列,默认删除所有列。
import pandas as pd
import numpy as np
index = pd.MultiIndex.from_tuples([('bird', 'falcon'), ('bird', 'parrot'), ('mammal', 'lion'), ('mammal', 'monkey')], names=['class', 'name'])
columns = pd.MultiIndex.from_tuples([('speed', 'max'), ('species', 'type')])
df = pd.DataFrame([(389.0, 'fly'), ( 24.0, 'fly'), ( 80.5, 'run'), (np.nan, 'jump')], index=index, columns=columns)
print(df)
print('\n')
df0 = df.reset_index()
print(df0)
print('\n')
df1 = df.reset_index(level=1)
print(df1)
print('\n')
df2 = df.reset_index(level='name')
print(df2)
如果列名(columns)有多个级别,决定被删除的索引将插入哪个级别,默认插入第一级(col_level=0)
import pandas as pd
import numpy as np
index = pd.MultiIndex.from_tuples([('bird', 'falcon'), ('bird', 'parrot'), ('mammal', 'lion'), ('mammal', 'monkey')], names=['class', 'name'])
columns = pd.MultiIndex.from_tuples([('speed', 'max'), ('species', 'type')])
df = pd.DataFrame([(389.0, 'fly'), ( 24.0, 'fly'), ( 80.5, 'run'), (np.nan, 'jump')], index=index, columns=columns)
print(df)
print('\n')
df1 = df.reset_index(level=0, col_level=0)
print(df1)
print('\n')
df2 = df.reset_index(level=0, col_level=1)
print(df2)
print('\n')
重置索引时被删除的索引只能插入一个级别,
import pandas as pd
import numpy as np
index = pd.MultiIndex.from_tuples([('bird', 'falcon'), ('bird', 'parrot'), ('mammal', 'lion'), ('mammal', 'monkey')], names=['class', 'name'])
columns = pd.MultiIndex.from_tuples([('speed', 'max'), ('species', 'type')])
df = pd.DataFrame([(389.0, 'fly'), ( 24.0, 'fly'), ( 80.5, 'run'), (np.nan, 'jump')], index=index, columns=columns)
print(df)
print('\n')
df0 = df.reset_index(level=0, col_level=0)
print(df0)
print('\n')
df1 = df.reset_index(level=0, col_level=0, col_fill=None)
print(df1)
print('\n')
df2 = df.reset_index(level=0, col_level=1, col_fill='species')
print(df2)
print('\n')
df3 = df.reset_index(level=0, col_level=0, col_fill='genus')
print(df3)
print('\n')
【1】https://blog.csdn.net/weixin_43298886/article/details/108090189