简体   繁体   中英

Fill Dataframe column with list that repeats for each item in another list

I have two lists of numbers that I want to use for a calculation, but they are not the same length.

list_1 = [123, 456, 789, 987]

list_2 = [321, 654]

Since there are 4x2 = 8 total combinations, I want to have them output like so:

       Calc_1                    Calc_2
Calc_of_list_1_num_1      Calc_of_list_2_num_1
Calc_of_list_1_num_2      Calc_of_list_2_num_1
Calc_of_list_1_num_3      Calc_of_list_2_num_1
Calc_of_list_1_num_4      Calc_of_list_2_num_1
Calc_of_list_1_num_1      Calc_of_list_2_num_2
Calc_of_list_1_num_2      Calc_of_list_2_num_2
Calc_of_list_1_num_3      Calc_of_list_2_num_2
Calc_of_list_1_num_4      Calc_of_list_2_num_2

I've been struggling with this and I'm just not sure how to approach it.

Use numpy's np.ufunc.outer :

Example Addition:

np.add.outer(list_1,list_2)

output:

array([[ 444,  777],
       [ 777, 1110],
       [1110, 1443],
       [1308, 1641]])

To create dataframe:

pd.DataFrame(np.add.outer(list_1,list_2), columns=list_2, index=list_1)

Output:

      321   654
123   444   777
456   777  1110
789  1110  1443
987  1308  1641

For multiplication use np.outer:

np.outer(list_1,list_2)

Output:

array([[ 39483,  80442],
       [146376, 298224],
       [253269, 516006],
       [316827, 645498]])

And for dataframe:

pd.DataFrame(np.outer(list_1,list_2), columns=list_2, index=list_1)

Output:

        321     654
123   39483   80442
456  146376  298224
789  253269  516006
987  316827  645498

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM