Home > Net >  How to loop through all values on two tables?
How to loop through all values on two tables?

Time:04-03

Would you do me a favor on how to do the expected result?

Initial Table A:

Name Score
Ken 500
John 600
Keith 700

Initial Table B:

Period
202201
202202
202203

My expected table is below

Name Period Score
Ken 202201 500
Ken 202202 500
Ken 202203 500
John 202201 600
John 202202 600
John 202203 600
Keith 202201 700
Keith 202202 700
Keith 202203 700

I believe the above questions should be answered before, but i have no idea on how to type my requirements in google. I have spent several hours on searching for it, but still dont know how to do.

Would someone help me on above?

Thanks!

CodePudding user response:

Here's a way to do it:

import pandas as pd
df_score = pd.DataFrame({'Name':['Ken', 'John', 'Keith'], 'Score':[500, 600, 700]})
df_period = pd.DataFrame({'Period':[202201, 202202, 202203]})
print(df_score)
print(df_period)
df_score['Period'] = [list(df_period['Period']) for _ in range(df_score.shape[0])]
df = df_score.explode('Period', ignore_index=True)
print(df)

Output:

    Name  Score
0    Ken    500
1   John    600
2  Keith    700
   Period
0  202201
1  202202
2  202203
    Name  Score  Period
0    Ken    500  202201
1    Ken    500  202202
2    Ken    500  202203
3   John    600  202201
4   John    600  202202
5   John    600  202203
6  Keith    700  202201
7  Keith    700  202202
8  Keith    700  202203

CodePudding user response:

try this it`s like join in sql https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html

import pandas as pd

df1 = pd.DataFrame({'Name': ['foo', 'bar', 'baz', 'fooz'],

                    'Score': [1, 2, 3, 5]})

df2 = pd.DataFrame({'Period': [202201, 202202, 202203]})

print(df1.merge(df2, how='cross'))
  • Related