1

Can some one help me with how I should transform the first dataframe into the second dataframe. I was trying something with groupby. How do I get df1 to df2 with groupby aggregation function in pandas?

df = pd.DataFrame(
    {
        "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
        "B": ["one", "one", "two", "three", "two", "two", "one", "three"],
        "C": [1,2,3,4,5,6,7,8]
    }
)


print(df)

df2 = pd.DataFrame(
    {
        "B_foo": ["one", "two", "two", "one","three"],
        "C_foo": [1,3,5,7,8],
        "B_bar": ["one", "three", "two", 0,0],
        "C_bar": [2,4,6,0,0],
    }
)
print(df2)

from dataframe df:

     A      B  C
0  foo    one  1
1  bar    one  2
2  foo    two  3
3  bar  three  4
4  foo    two  5
5  bar    two  6
6  foo    one  7
7  foo  three  8

to daframe df2

   B_foo  C_foo  B_bar  C_bar
0    one      1    one      2
1    two      3  three      4
2    two      5    two      6
3    one      7      0      0
4  three      8      0      0
Roos
  • 11
  • 5
  • `dict(tuple(df.groupby('A')))['foo'][['B', 'C']].reset_index(drop=True).join(dict(tuple(df.groupby('A')))['bar'][['B', 'C']].reset_index(drop=True), lsuffix='_foo', rsuffix='_bar').fillna(0)` – RJ Adriaansen Nov 19 '21 at 08:36
  • Thanks. But this is a very complicated way, since the column values (foo and bar are defined). The dataframe where I want to apply more extensive – Roos Nov 19 '21 at 09:33

0 Answers0