1

Given the following data frames:

import pandas as pd
k=pd.DataFrame({'A':[1,1],'B':[3,4]})
e=pd.DataFrame({'A':[1,1],'B':[6,7]})
k
    A   B
0   1   3
1   1   4

e
    A   B
0   1   6
1   1   7

I'd like to apply a group-by sum in a loop, but doing so does not seem to modify the data frames.

Here's what I've tried:

for d in dfsout:
    d=d.groupby(d.columns[0]).apply(sum)
    print(d)

When I print d in the loop, it shows that the correct operation is occurring...

   A  B
A      
1  2  7
   A   B
A       
1  2  13

...but then when I print data frames k and e, they have not been modified.

k
    A   B
0   1   3
1   1   4

e
    A   B
0   1   6
1   1   7

Update

I also tried using it as a function (works in loop, still does not modify):

def moddf(d):
    return d.groupby(d.columns[0]).apply(sum)
for d in dfsout:
    d=moddf(d)
    print(d)

Thanks in advance!

3
  • It is almost the same with your previous question , you can using the same method . Commented Aug 4, 2017 at 17:37
  • @Wen - I tried using that method but it would not modify the data frames in the way I needed. I did not do it in the same loop, however, as I'm not sure how. Commented Aug 4, 2017 at 17:40
  • @DanceParty2 I posted my answer again ~ Commented Aug 4, 2017 at 19:13

2 Answers 2

0

Ok , you can try this

import pandas as pd
k=pd.DataFrame({'A':[1,1],'B':[3,4]})
e=pd.DataFrame({'A':[1,1],'B':[6,7]})
fields=['k','e']
dfsout=[k,e]
variables = locals()
for d,name in zip(dfsout,fields):
    variables["{0}".format(name)]=d.groupby(d.columns[0]).apply(sum)


k
Out[756]: 
   A  B
A      
1  2  7
e
Out[757]: 
   A   B
A       
1  2  13
Sign up to request clarification or add additional context in comments.

1 Comment

What is the reason for downvote?
0

This worked:

First, define the function

def moddf(d):
    return d.groupby(d.columns[0]).apply(sum)

Next, reassign modified data frames like this:

k,e=[moddf(x) for x in dfsout]

or

dfsout2=[moddf(x) for x in dfsout]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.