Extract values from a list and put them into a dataframe in Python

Viewed 177

I have data in a list (numbers, numbers). I want to subtract the trailing number from this data and put it in a dataframe. The number before the comma in the list is equal to the index of the dataframe.

--------------Below is a code example. -------------

import pandas as pd

test_list=[(1,124),(2,234),(3,344)]
test_data={
    'index' : [1,2,3],
    'data1' : [3,5,6],
    'data2' : [2,5,6]
}


test_df  =pd.DataFrame(test_data)
test_df

Example Image

enter image description here

I want to add test_list to the last column of test_df. As an example, I made a small list and data frame with some examples. Can I put it like this?

1 Answers

You can create a dataframe out of test_list, and merge it to the test_df

>>> test_df.merge(pd.DataFrame(test_list, columns=['index', 'number']))

   index  data1  data2  number
0      1      3      2     124
1      2      5      5     234
2      3      6      6     344

Another option is to use dictionary instead of list of tuples, then use pandas.Series.map to map the values:

>>> test_d = {1: 124, 2: 234, 3: 344}
>>> test_df['number']=test_df['index'].map(test_d)
>>> test_df
   index  data1  data2  number
0      1      3      2     124
1      2      5      5     234
2      3      6      6     344
Related