Pandas concat DataFrames - 保持索引的原始顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42361589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:01:47  来源:igfitidea点击:

Pandas concat DataFrames - keep original order of index

pythonpandasdataframeconcat

提问by warrenfitzhenry

I am trying to concat two dataframes:

我正在尝试连接两个数据框:

df2:
CU  Pmt  2017-02-01
h    b        15
h    d        12
h    a        13

and df1:

和 df1:

CU  Pmt  'Total/Max/Min'
h    b        20
h    d        23 
h    a        22
a    b        16
a    d        13
a    a        14

such that df3:

这样df3:

CU  Pmt  2017-02-01  2017-02-02
h    b      15           20
h    d      12           23
h    a      13           22
a    b      NaN          16
a    d      NaN          13
a    a      Nan          14

I am using a multi index of index_col = [0,1] for both

我对两者都使用了 index_col = [0,1] 的多索引

This is what I have:

这就是我所拥有的:

date = '2017-02-02'
df1 = pd.read_csv(r'Data17-0217-02-02\Aggregated\Aggregated_Daily_All.csv', usecols=['CU', 'Parameters', 'Total/Max/Min'], index_col =[0,1])
df1 = df1.rename(columns = {'Total/Max/Min':date})

df2 = pd.read_csv(r'Data17-02\MonthlyData\February2017.csv', index_col = [0,1])
df3  = pd.concat([df2, df1], axis=1)
df3.to_csv(r'Data17-02\MonthlyData\February2017.csv')

However, df3 is coming out as:

但是,df3 的结果是:

CU  Pmt  2017-02-01  2017-02-02
a    a      NaN          14
a    b      NaN          16
a    d      Nan          13
h    a      13           22
h    b      15           20
h    d      12           23

Which has CUand Pmt(the two index columns) in alphabetical order. How is it possible to keep the original order, so that for all new indexes added for a new date, they are added at the bottom?

其中有CUPmt(两个索引列)按字母顺序排列。如何保持原始顺序,以便为新日期添加的所有新索引都添加到底部?

回答by jezrael

You can try reindexif values of df1.indexcontains values of df2.index:

reindex如果值df1.index包含以下值,您可以尝试df2.index

df3  = pd.concat([df2, df1], axis=1).reindex(df1.index)
print (df3)
        2017-02-01  'Total/Max/Min'
CU Pmt                             
h  b          15.0               20
   d          12.0               23
   a          13.0               22
a  b           NaN               16
   d           NaN               13
   a           NaN               14