Python将新行添加并排序到DataFrame中

时间:2019-11-30 09:47:35

标签: python dataframe

我想在数据框中添加一行,并希望在插入后对数据框进行排序。

我已经添加了该行并重置了数据帧索引,但没有成功。

如何解决此问题?谢谢您提前提出建议。

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   

1 个答案:

答案 0 :(得分:0)

我认为大熊猫的searchsorted想要返回插入位置。

每个插入的排序值听起来都很糟糕。但是,如果您只需要在所有插入之后排序一次,那就没问题了。