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'])

collect = []
for i in range(5):
    collect.append(df0.mean())
    collect.append((i**2+2))

Here, I obviously made it simpler by looping over the same dataframe 5 times but in my actual data, every iteration goes through different columns in the dataframe. Anyway, I want an end result of:

 A    B   i
3.0  2.6  2
3.0  2.6  3
3.0  2.6  6
3.0  2.6  11
3.0  2.6  18

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

Edit: I changed the third column a bit so that one can see that it's different from a simple index column.

2 Answers 2

1

You can do it with transform

df0.groupby([1]*len(df)).transform('mean')
   A    B
0  3  2.6
1  3  2.6
2  3  2.6
3  3  2.6
4  3  2.6
Sign up to request clarification or add additional context in comments.

3 Comments

How do I add the third column here? In the above example, it is the index column but in my code, it's another result, so I need it as another column.
@NewbieAF df0.groupby([1]*len(df)).transform('mean').reset_index()
That third column is not the index column, it’s a column of completely different results (I know I was lazy in the example in my question), so this still doesn’t quite work. I need to create this third column using the specific numbers appended in the for-loop. I edited the question to make it a bit clearer.
0

Try this:

A_mean, B_mean = df0.mean()
result = [[A_mean, B_mean, i**2+2] for i in range(len(df0))]
collect = pd.DataFrame(result, columns=['A', 'B', 'i'])

Comments

Your Answer

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