Home > OS >  How to add one list to one cell at a time in a pandas dataframe
How to add one list to one cell at a time in a pandas dataframe

Time:12-13

I have a for loop which prints a list of hex strings for each iteration

for i in range(0, 10):
    print([str(hex(i))[::2], str(hex(i*10))[::2], str(hex(i 10))[::2]])

the output is

['00', '00', '0a']
['01', '0a', '0b']
['02', '01', '0c']
['03', '01', '0d']
['04', '02', '0e']
['05', '03', '0f']
['06', '03', '01']
['07', '04', '01']
['08', '05', '01']
['09', '05', '01']

I want to read the lists into one cell at a time such that the dataframe should look like this

idx NEWcoL
1 ['00', '00', '0a']
2 ['01', '0a', '0b']
3 ['02', '01', '0c']
4 ['03', '01', '0d']
5 ['04', '02', '0e']
6 ['05', '03', '0f']
7 ['06', '03', '01']
8 ['07', '04', '01']
9 ['08', '05', '01']
10 ['09', '05', '01']

CodePudding user response:

Can you try this:

my_list=[]
for i in range(0, 10):
    my_list.append([str(hex(i))[::2], str(hex(i*10))[::2], str(hex(i 10))[::2]])
df=pd.DataFrame({'NEWcoL':my_list}).reset_index(names='idx')

Output:

   idx        NEWcoL
0    0  [00, 00, 0a]
1    1  [01, 0a, 0b]
2    2  [02, 01, 0c]
3    3  [03, 01, 0d]
4    4  [04, 02, 0e]
5    5  [05, 03, 0f]
6    6  [06, 03, 01]
7    7  [07, 04, 01]
8    8  [08, 05, 01]
9    9  [09, 05, 01]

CodePudding user response:

hex bulitin function already returns a string representation of an integer, no need to str additionally. Here's simple one-liner:

In [362]: df = pd.DataFrame({'idx':range(1, 11), 'newcol':[[hex(i)[::2], hex(i*10)[::2], hex(i 10)[::2]] for i in range(10)]})

In [363]: df
Out[363]: 
   idx        newcol
0    1  [00, 00, 0a]
1    2  [01, 0a, 0b]
2    3  [02, 01, 0c]
3    4  [03, 01, 0d]
4    5  [04, 02, 0e]
5    6  [05, 03, 0f]
6    7  [06, 03, 01]
7    8  [07, 04, 01]
8    9  [08, 05, 01]
9   10  [09, 05, 01]

CodePudding user response:

import pandas as pd
df = pd.DataFrame(index=[0], columns=['NEWcoL'])
for i in range(0, 10):
    df.loc[i, 'NEWcoL']=[str(hex(i))[::2], str(hex(i*10))[::2], str(hex(i 10))[::2]]

df.index = np.arange(1, len(df)   1)
df.index.names = ['idx']


           NEWcoL
idx              
1    [00, 00, 0a]
2    [01, 0a, 0b]
3    [02, 01, 0c]
4    [03, 01, 0d]
5    [04, 02, 0e]
6    [05, 03, 0f]
7    [06, 03, 01]
8    [07, 04, 01]
9    [08, 05, 01]
10   [09, 05, 01]
  • Related