Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

python - Pandas create a frame whose entries are the value of a function applied to the respective entries of other DataFrames

I have tree frames, lets say:

ID    A  B   | ID    A B  | ID    A B
john  *  1   | john  # 2  | john  @ 3
paul  1  1   | paul  2 2  | paul  3 3
jones 1  1   | jones 2 2  | jones 3 3

and I have to create a new dataframe where each entry is the result of a function whose arguments are the respective entries of the three frames

ID    A        B
john f(*,#,@) f(1,2,3)
...

I'm new to pandas and the only approach that I would know how to do is to turn the frames into numpy arrays and work on them like you would do on three matrices, but I would prefer to solve this problem the panda's way.

I already tried looking for other questions on SO but couldn't find anything, it is possible that that's due to how I've formulated my question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Not really sure exactly what is what you're doing, but here is something:

# Define dummy function (f)
def f(x):
    # you can use here x.name, x.A, x.B 
    # >>> x.name
    # 'paul'
    # >>> x.A
    # ['1', '2', '3']
    # >>> X.B
    # [1, 2, 3]
    return x

>>> df1
      ID  A  B
0   john  *  1
1   paul  1  1
2  jones  1  1

>>> df2
      ID  A  B
0   john  #  2
1   paul  2  2
2  jones  2  2

>>> df3
      ID  A  B
0   john  @  3
1   paul  3  3
2  jones  3  3

>>> pd.concat([df1,df2,df3]).groupby('ID').agg(list).apply(f, axis=1)
               A          B
ID
john   [*, #, @]  [1, 2, 3]
jones  [1, 2, 3]  [1, 2, 3]
paul   [1, 2, 3]  [1, 2, 3]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...