今天contact了几个dataframe文件,由于对最终处理数据的行数有限制,所以我选择随机删除几行数据,在使用drop中的index删除是发现同时删掉了好多行,检查后才发现index有重复,故查找了重新设置index的方法,以此记录。
代码如下:
import pandas as pd
df1=pd.DataFrame({'one':[1,2,3,4],
'two':[4,5,6,7]})
df2=pd.DataFrame({'one':[8,9,10,11],
'two':[12,13,14,15]})
df3=pd.concat([df1,df2])
print(df3)
结果如下:
one two
0 1 4
1 2 5
2 3 6
3 4 7
0 8 12
1 9 13
2 10 14
3 11 15
由上可知index重复,若直接按照index删除行数,则会同时删除多行。
代码如下:
df3.drop(index=[0],inplace=True)
print(df3)
结果如下:
one two
1 2 5
2 3 6
3 4 7
1 9 13
2 10 14
3 11 15
故应当从新设置index
df3=df3.reset_index(drop=True)
print(df3)
结果如下:
one two
0 2 5
1 3 6
2 4 7
3 9 13
4 10 14
5 11 15
或者:
df5=pd.concat([df1,df2])
df5.index=range(len(df5))
print(df5)
结果如下:
one two
0 1 4
1 2 5
2 3 6
3 4 7
4 8 12
5 9 13
6 10 14
7 11 15