简体   繁体   中英

Appending by name with python pandas multiindex dataframe

I am tryining to append a pandas multiindex dataframe within a loop.

My multiindex dataframe looks a little like this (let's call it df1):

method     (TestAa, TestAb)
properties level     l      r
0          0.0   144.6  161.4
1          0.1   146.3  161.4
2          0.2   148.0  161.4
3          0.3   149.7  161.4
4          0.4   151.3  161.4

Now I want to append another dataframe (df2) to it, so that the appended dataframe is sorted by the name "method" (which btw is a string tuple). In my mind it should look like that:

method     (TestAa, TestAb)     /  (TestBa, TestBb)                   
properties level       l      r /  level       l      r
0            0.0   144.6  161.4 /    0.0   150.6  161.4
1            0.1   146.3  161.4 /    0.1   151.3  161.4
2            0.2   148.0  161.4 /    0.2   152.0  161.4
3            0.3   149.7  161.4 /    0.3   153.7  161.4
4            0.4   151.3  161.4 /    0.4   155.3  161.4

In other words I want to add another column to an existing dataframe.

Right now I am creating the df as described in the doc :

method = tuple([TestAa, TestAb])
columns = [[method]*3,["level", "l", "r"]]
tuples = list(zip(*columns))
index = pd.MultiIndex.from_tuples(tuples, names=['method', 'properties'])
df1= pd.DataFrame(columns=index, data=data, dtype=np.float)

Thank you in advance!

我相信只需要concat

df = pd.concat([df1, df2], axis=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM