Skip to content
Advertisement

Python- trying to make new list combining values from other list

I’m trying to use two columns from an existing dataframe to generate a list of new strings with those values. I found a lot of examples doing something similar, but not the same thing, so I appreciate advice or links elsewhere if this is a repeat question. Thanks in advance!

If I start with a data frame like this:

JavaScript

I want to make a list that looks like new_ids=[‘a_1′,’b_2′,’c_3’] where values are from combining values in row 0 for id1 with values for row 0 for id2 and so on.

I started by making lists from the columns, but can’t figure out how to combine them into a new list. I also tried not using intermediate lists, but couldn’t get that either. Error messages below are accurate to the mock data, but are different from the ones with real data.

JavaScript

Advertisement

Answer

JavaScript

output:

JavaScript

your approaches(corrected):

JavaScript

points:

  1. in first approach, when you loop on data, i and j are data, not indices, so use them as data and convert them to string.
  2. join get list as data and simply define a list using 2 data: [str(i),str(j)] and pass to join
  3. in second approach, you can get every element of every column using df['id1'][i] and you don’t need values that return all elements of column as a numpy array

if you want to use values:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement