我想在数据框中添加一行,并希望在插入后对数据框进行排序。
我已经添加了该行并重置了数据帧索引,但没有成功。
如何解决此问题?谢谢您提前提出建议。
import pandas as pd
def diff(first, second):
second = set(second)
return [item for item in first if item not in second]
df = pd.DataFrame({"Date":[
'2015/12/25',
'2015/12/26',
'2015/12/27',
'2015/12/28',
'2015/12/29',
'2015/12/30',
'2015/12/31'
],
"X":["X","A","A","X","","","X"]
})
df2 = pd.DataFrame({"Date":[
'2015/12/25',
'2015/12/28',
'2015/12/29',
'2015/12/30',
'2015/12/31'
],
"X":["X","A","A","X",""]
})
diff_df = pd.merge(df, df2, how='outer', indicator='Exist')
diff_df = diff_df.loc[diff_df['Exist'] != 'both']
prevDay = int(diff_df['Date'].values[0].rsplit('/', 1)[-1]) - 1
prevDate = diff_df['Date'].values[0].rsplit('/', 1)[-2] + "/" + str(prevDay)
df3 = pd.DataFrame({"Date":[diff_df['Date'].values[0]], "X":["Q"]})
df2 = df2.sort_index(axis=1, ascending=True)
df2 = df2.append(df3)
df2 = df2.reset_index(drop=True)
print(df2)
实际输出:
0 2015/12/25 X
1 2015/12/28 A
2 2015/12/29 A
3 2015/12/30 X
4 2015/12/31
5 2015/12/26 Q
预期输出:
0 2015/12/25 X
1 2015/12/26 Q
2 2015/12/28 A
3 2015/12/29 A
4 2015/12/30 X
5 2015/12/31