Get Dataframe two columns and convert to dic list

Question:

I need to generate a dataframe with pandas with an object with two columns, where the first column represents a number x which must be the sequence of this, for example 0-2-4-6-8 ….. up to 100. The second column is the accumulated of this by position (for example 0-2-6-10-18). Then deliver the result in list format example {‘column1’: [0,2,4,6,8……], ‘column2’:[0,2,6,10,18]}

I have declared two arrays for number and accumulated
With a for loop I go through and insert the multiples of the number in column 1
In the same way I am adding the accumulated

number_value = 2
numbers = []
accumulated = []
sum = 0
for i in range (0,100):
  if i%value_number == 0:
     sum += i
     numbers.append(i)
     accumulated.append(sum)
Asked By: francis

||

Answers:

import pandas as pd

df = pd.DataFrame({'column1': [0,2,4,6,8......], 'column2':[0,2,6,10,18]})

df.to_records() # (or is it to_dict())

Play with the options..

Answered By: Oren

You can use:

import pandas as pd
import numpy as np

a = np.arange(0, 100+1, number_value)
b = np.cumsum(a)

df = pd.DataFrame({'column1': a, 'column2': b})
d = df.to_dict('list')

Output:

>>> df.head(10)
   column1  column2
0        0        0
1        2        2
2        4        6
3        6       12
4        8       20
5       10       30
6       12       42
7       14       56
8       16       72
9       18       90

>>> d
{'column1': [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100], 
 'column2': [0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462, 506, 552, 600, 650, 702, 756, 812, 870, 930, 992, 1056, 1122, 1190, 1260, 1332, 1406, 1482, 1560, 1640, 1722, 1806, 1892, 1980, 2070, 2162, 2256, 2352, 2450, 2550]}
Answered By: Corralien

You can continue developing your problem with what you currently have. Look at this example which is similar to what you are missing:

# creating lists (with your for loop)
l1 =[0, 2, 4, 6, 8...............]
l2 =[0, 2, 6, 12, 20, 30............]
  
# creating the DataFrame
data= pd.DataFrame(list(zip(l1, l2)), columns = ['numbers', 'accumulated'])
data= data.to_dict(orient='list')
Answered By: cr7
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.