1

I'm trying to create a pandas DataFrame to collect everything I have but I'm having difficulty combining numpy arrays in a list to create a single array.

Suppose I have the following data:

df0 = pd.DataFrame([[1,2],[2,2],[3,1],[4,4],[5,4]], columns = ['A','B'])

switch = [[1,3,4],[2,5]]

collect = []
for lists in switch:
    mask = df0.A.isin(lists)
    avg = df0[mask].mean().round(2)
    collect.append(avg)
    collect.append((avg[0]**2+avg[1]+2).round(2))

This produces the following output:

[A    2.67
 B    2.33
 dtype: float64,
 11.46,
 A    3.5
 B    3.0
 dtype: float64,
 17.25]

However, I want the following output:

 A     B      C
2.67  2.33  11.46
3.5   3.0   17.25

but I can't create a 2x3 matrix because len(collect) is 4. I think I'm not using .append in the right way in the for-loop. How do I create an array (or a list) such that len(collect) is either 2 or 6? I'm thinking if it's of length 2, we can simply transpose collect or of it's of length 6, we can reshape it.

2 Answers 2

1

My approach:

(df0.groupby(pd.Series({x-1:k for k,v in enumerate(switch) for x in v}))
    .mean()
    .assign(C=lambda x: x['A']**2 + x['B']+2)
    .round(2)
)

Output:

      A     B      C
0  2.67  2.33  11.44
1  3.50  3.00  17.25
Sign up to request clarification or add additional context in comments.

Comments

0

other solution is here

import pandas as pd
df0 = pd.DataFrame([[1,2],[2,2],[3,1],[4,4],[5,4]], columns = ['A','B'])

switch = [[1,3,4],[2,5]]

collect = []
def calc(first,second):
   cal=((first**2+second+2).round(2))
return cal

for lists in switch:
   mask = df0.A.isin(lists)
   avg = df0[mask].mean().round(2)
   collect.append(avg)

df=pd.DataFrame(collect)
df['c']='None'
for i in range(2) : 
   list=[df.apply(lambda row : calc(df.loc[i, "A"], df.loc[i, "B"]),axis=1) ]
   df['c'][i]=list[0][i]


print(df)

output

    A   B   c
0   2.67    2.33    11.46
1   3.50    3.00    17.25

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.