Home > Mobile >  Similar Columns Split Into Multiple Dataframes
Similar Columns Split Into Multiple Dataframes

Time:08-12

Given that I have a pandas dataframe:

item#   name    value   price   item#   name    value   price
1   testname    testvalue   12  5   testname5   testvalue5  12
2   testname    testvalue   12  7   testname7   testvalue7  21
3   testname    testvalue   12  9   testname9   testvalue9  4

Where multiple dataframes are side-by-side each other how do I split them into different dataframes. In this case there would be two dataframes that can be taken.There's also the case where this could reach 4 or 5 similar columns. Any way to parse them properly?

CodePudding user response:

IIUC, you can use:

l = [g for k,g in df.groupby(df.groupby(df.columns, axis=1).cumcount(), axis=1)]

output:

[   item#      name      value  price
 0      1  testname  testvalue     12
 1      2  testname  testvalue     12
 2      3  testname  testvalue     12,
    item#       name       value  price
 0      5  testname5  testvalue5     12
 1      7  testname7  testvalue7     21
 2      9  testname9  testvalue9      4]

CodePudding user response:

If you would like to manually specify column indices for the new dataframes, you can use .iloc:

df1 = df.iloc[:, 0 : 4]
df2 = df.iloc[:, 4 : 8]
  • Related