0

I'm very new to pandas and dataframes.

I have two lists in python which contains columns and values that needs to be inserted for that columns in a row.

For Ex:

col_list = ['column1', 'column3', 'column4', 'column6', ...]
val_list = ['value1', 'value3', 'value4', 'value6', ...]

How can I insert these values from val_list in columns in col_list for a specific row.

And I need to iterate multiple times.

These value and column list will change for every iteration but the order of column1 - value1, column2 - value2 doesn't change.

If the ith element in col_list is col-i, then ith element in val_list will be val-i.

How can I enter data in only specific columns that are in col_list into pandas dataframe.

  • Possible duplicate of [Insert a row to pandas dataframe](https://stackoverflow.com/questions/24284342/insert-a-row-to-pandas-dataframe) – G. Anderson Oct 25 '18 at 15:57
  • Note: You can't insert only data into certain columns in a new row, the rest of the row will be `NaN`. If you want to update an existing row, then you can use `loc` and `iloc` indexing to get to where you want – G. Anderson Oct 25 '18 at 15:58
  • The remaining column values can be `Nan`. No problem with that. Is there a way to do that? – Tyrion Lannister Oct 25 '18 at 15:59
  • As in the link above, [Insert a row to pandas dataframe](https://stackoverflow.com/questions/24284342/insert-a-row-to-pandas-dataframe) – G. Anderson Oct 25 '18 at 16:01
  • Here is a great resource for future uses: http://pbpython.com/pandas-list-dict.html – B. Cratty Oct 25 '18 at 16:03

1 Answers1

0
my_pd = pd.DataFrame(np.array(val_list)).T
my_pd.columns = col_list
pd.concat([a, my_pd], ignore_index=True)

I don't really see this in other answers, but here is a way to use concat to join your list to the end of the pandas dataframe. It's tricky though, usually it's best to iterate through all the list you want to join, create a new DataFrame off that and then joining those 2 df together, it will be much easier and faster.

Rocky Li
  • 5,641
  • 2
  • 17
  • 33