Home > other >  How to save a list in a dataframe cell?
How to save a list in a dataframe cell?

Time:12-16

I need to store a list in a dataframe cell.

How can I save the list into one column? and how can it be read and parsed from this cell?

I have tried this code to generate temporary dataframe in cycle:

newlist = [1267, 1296, 1311, 1320, 1413, 1450]

temp = pd.DataFrame(
      {
        'window_index_num': i,
        'window_identifiers': newlist, ### here is the problem!
        'left_pulse_num':w_left_pulse_num,
        'right_pulse_num': w_right_pulse_num,
        'idx_of_left_pulse': idx_of_left_pulse,
        'idx_of_right_pulse': idx_of_right_pulse, 
        'left_pulse_pos_in_E': left_pulse_pos_in_E,
        'right_pulse_pos_in_E':right_pulse_pos_in_E,
        'idx_window_left_border': idx_window_left_border,
        'idx_window_right_border': idx_window_right_border,
        'left_win_pos_in_E': left_win_pos_in_E,
        'right_win_pos_in_E': right_win_pos_in_E,
        'window_width': points_num_in_current_window, 
        'window_width_in_E': window_width_in_E,
        'sum_pulses_duration_in_E': sum_pulses_duration_in_E,
        'sum_pulse_sq': sum_pulse_sq,
        'pulse_to_window_rate': pulse_to_window_rate,
        'max_height_in_window': max_height_in_window,
        'min_height_in_window': window_min_val 
       }, index=[i]
    )

when I run it, I have an error ValueError: Length of values (6) does not match length of index (1)

I have tried to use this approach, but it didn't help.

...
    'min_height_in_window': window_min_val 
       }, index=[i]
    )
   
    temp['window_identifiers']=temp['window_identifiers'].astype('object')
    temp['window_identifiers']=all_ids_in_window
    windows_df = pd.concat([windows_df, temp])

CodePudding user response:

You can try changing 'window_identifiers': newlist, to 'window_identifiers': [newlist],. For example:

import pandas as pd

df = pd.DataFrame({'x': 1, 'y': 2, 'z': [['i', 'j', 'k']]}, index=[1])
print(df)

Output:

   x  y          z
1  1  2  [i, j, k]

CodePudding user response:

Pandas is trying to unfold that list into an entire column, but the index is one value long. Either do this without the index to unfold.

df = pd.DataFrame({'x':1,'y':2, 'z': newList})

Or make the column a nested list.

  • Related