Fill dataframe row-whise from a list, where every nth values begins a new row

Issue

hopefully you can help me.

I have created a dataframe with 25 columns, rows are empty so far.

column_name = df[0].values.tolist()[0:25]
column_name

['Time:',
 '\tDC_Verbrauch:',
  '\tDC_Verbrauch_Ueberlauf:',
  '\tHVEM_IstLeistungNA:',
  '\tHVLM_Restladezeit_HV_Bat_02:',
  '\tHVLM_Bat_laden_aktiv:',
  '\tHVLM_Ladeart:',
  '\tHVLM_Stecker_Status:',
  '\tKBI_angez_Geschw:',
  '\tKBI_Inhalt_Tank:',
  '\tKBI_Aussen_Temp_gef:',
  '\tMO_KVS:',
  '\tMO_KVS_Ueberlauf:',
  '\tMO_Verbrauch_EM_Ges:',
 ...

Then deleted the \t and put these list of 25 values as column names of an empty dataframe.

Now I have a list that contains 16350 values.

Every 25th value should start a new row. Which means I will have later have 654 rows with 25 filled columns. So from list shape (16350,1) to a dataframe (654,25)

values
 ['1654786811.282628',
 '786Unit_WattSecond',
 '0',
 '13700Unit_Watt',
 '1370Unit_Minut',
 '0',
 '2',
 '2',

 ...

 '1810Unit_WattSecond',
 '0',
 '1654786811.381790',
 '83Unit_WattSecond',
 '1',
 '4150Unit_Watt',
 '415Unit_Minut',
 '1',
 '3',
 '3',
 '26.56Unit_KiloMeterPerHour',

The beginning of the first row is ‘1654786811.282628’ – Beginning of the second: ‘1654786811.381790’

So I need a row-whise filling of a dataframe out of one list of values.

Best Regards
thaclone

Solution

you can use numpy.reshape to achieve that.

See on a simpler data of 3 columns:

data = [ "Tom", 32, 85, "Jerry", 35, 50, "Mickey", 40, 10, "Mouse", 20, 12 ]
pd.DataFrame(np.array(data).reshape(4,3), columns = ["name", "age", "height"])

Answered By – Ales Novak

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published