4

I have a list with some counts with 5 elements.

counts = [33, 35, 17, 38, 29]

This counts list is updated with new numbers every day. So I wanted to create a dataframe and append the counts data as a new row every day. Every element of the list should appear in separate column in the dataframe. What i want to do is the following:

df = pd.DataFrame(columns = ['w1', 'w2', 'w3', 'w4', 'w5'])
df = df.append(counts)

but instead of adding counts data as a row, it adds a new column. Any help on how to do this correctly?

Assume counts on day0 is [33, 35, 17, 38, 29] and on day1 is [30, 36, 20, 34, 32], what i want is the following as output:

      w1 w2 w3 w4 w5
    0 33 35 17 38 29
    1 30 36 20 34 32

where index represent the day at which counts were taken. any help?

HT121
  • 431
  • 2
  • 6
  • 14

3 Answers3

10

Appending to DataFrame is possible, but because slow if many rows, better is create list of lists and create DataFrame by contructor:

counts = [33, 35, 17, 38, 29]
counts1 = [37, 8, 1, 2, 0]

L = [counts, counts1]
df = pd.DataFrame(L, columns = ['w1', 'w2', 'w3', 'w4', 'w5'])
print (df)

   w1  w2  w3  w4  w5
0  33  35  17  38  29
1  37   8   1   2   0

But if need it, e.g. appenf one row daily only, then is necessary create Series with same index values like columns:

df = pd.DataFrame(columns = ['w1', 'w2', 'w3', 'w4', 'w5'])

counts = [33, 35, 17, 38, 29]

s = pd.Series(counts, index=df.columns)
df = df.append(s, ignore_index=True)
print (df)
   w1  w2  w3  w4  w5
0  33  35  17  38  29
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
8

If you know day0 and day1 in the beginning, then you want to construct it as jezrael suggests.

But I'm assuming that you want to be able to add a new row in a loop.

Solution with loc

When using loc you need to use an index value that doesn't already exist. In this case, I'm assuming that we are maintaining a generic RangeIndex. If that is the case, I'll assume that the next index is the same as the length of the current DataFrame.

df.loc[len(df), :] = counts
df

   w1  w2  w3  w4  w5
0  33  35  17  38  29

Let's make the loop.

day0 = [33, 35, 17, 38, 29]
day1 = [30, 36, 20, 34, 32]

for counts in [day0, day1]:
  df.loc[len(df), :] = counts

df

     w1    w2    w3    w4    w5
0  33.0  35.0  17.0  38.0  29.0
1  30.0  36.0  20.0  34.0  32.0
piRSquared
  • 285,575
  • 57
  • 475
  • 624
0
ran_list =[]
for i in list(range(0,12)):
     ran_list.append(round(random.uniform(133.33, 266.66),3))
print(ran_list)

df = pd.DataFrame([ran_list])
df
thangaraj1980
  • 141
  • 2
  • 11