Python函数:reset_index()
resert_index()函数:
Series.reset_index(level=None, drop=False, name=NoDefault.no_default, inplace=False)
作用: 用索引重置生成一个新的DataFrame或Series。当索引需要被视为列,或者索引没有意义,需要在另一个操作之前重置为默认值时。在机器学习中常常会对索引进行一定的处理,用于是否保留原有的索引。
例子:
import pandas as pd
df = pd.DataFrame(data={'A':[1,2,3],'B':[4,5,6],'C':[7,8,9]})
print(df)
print('\n')
print(df.reset_index()) # 会将原来的索引index作为新的一列
print('\n')
print(df.reset_index(drop=True)) # 使用drop参数设置去掉原索引
print('\n')
结果:
A B C
0 1 4 7
1 2 5 8
2 3 6 9
index A B C
0 0 1 4 7
1 1 2 5 8
2 2 3 6 9
A B C
0 1 4 7
1 2 5 8
2 3 6 9
读懂代码中resert_index():
def concat_detail(x):
return pd.Series({'备注':';'.join(x['detail'])})
df2=df1[['cwhxzqh','detail']].groupby('cwhxzqh').apply(concat_detail).reset_index()
df2
将df1中原来的索引作为一个列,列名为 index
欢迎批评指正(●'◡'●)
部分来源:
reset_index()函数_lady_chen的博客-CSDN博客_reset_index函数【pandas】reset_index函数详解_为什么昵称不能重复的博客-CSDN博客_reset_index函数 pandas.DataFrame.reset_index — pandas 1.4.1 documentation
来源:小小白23333