简体   繁体   中英

Populating a dictionary of lists with values from 2 columns of a DataFrame

If I have a DataFrame that stores values from 2 columns (A & B) from a CSV file, how would I populate a dictionary using a for loop to get the values from the DataFrame?

I need to store the rows of AB pairs like this.. A_&_B_sets = {1:[A1,B1],2:[A2,B2],…}

A_&_B_sets = {1:[A1,B1],2:[A2,B2],…}
for i in (1,n+1):
  A_&_B_sets[i] = i * I

I am quite lost. Any help greatly appreciated.

If you have df like this:

   Column A  Column B
0         1         4
1         2         5
2         3         6

Then you can do:

A_and_B_sets = {}
for i, (_, row) in enumerate(df.iterrows(), 1):
    A_and_B_sets[i] = [row["Column A"], row["Column B"]]

print(A_and_B_sets)

to print:

{1: [1, 4], 2: [2, 5], 3: [3, 6]}

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