Home > database >  Python - append a list with uncertain length to specific columns in order
Python - append a list with uncertain length to specific columns in order

Time:10-25

I have a program returns a list with uncertain length of numbers each time, and I want to append the list to dataframe. Each time, I know the column order to append but I don't know the length of the list.

df = DataFrame(columns = ['A', 'B', 'C', 'D', 'E', 'F']

If the column order is B, C, D, E, F and the list return 3 numbers (2, 4, 6), then it will be

A B C D E F
2 4 6

If the column order is E, D, C, B, A and the list return 2 numbers (4, 6), then it will be

A B C D E F
2 4 6
6 4

Again I know the column order but I don't know how many numbers will be returned.

CodePudding user response:

Try using .loc:

import pandas as pd 

data = pd.DataFrame(columns=["A", "B", "C", "D", "E", "F"])

datum = [2, 3, 4]
order = ["A", "C", "D"]

data.loc[len(data.index), order] = datum
print(data)

This gives:

   A    B  C  D    E    F
0  2  NaN  3  4  NaN  NaN

data.index stores the axis labels for data.

Here, it is Int64Index([0], dtype='int64'). Getting the length of this object allows us to add a new row to the data frame when used with data.loc.

For example, if we try:

order = ["A", "C", "F", "D"]
datum = [-1, 0, 100, 5]

data.loc[len(data.index), order] = datum
print(data, "\n")
print("Index of data:", data.index)

it gives:

    A    B  C  D    E    F
0   2  NaN  3  4  NaN  NaN
1  -1  NaN  0  5  NaN  100

Index of data: Int64Index([0, 1], dtype='int64')

CodePudding user response:

say col order list is col_names and list with unknown variables is num_list then you can try;

for i,c in enumerate(col_names):
   if i > len(num_list):
      break
   df.iloc[x][c] = num_list[I]

Update or

for i,num in enumerate(num_list):
   df.iloc[x][col_names[i]] = num

Not elegant. But will do the job. x is the location of dataframe for the datapoint.

  • Related