You are first adding R0Cx and then R1Cxy. You need to add RxCy. So try:

newlist = []
row = A
col = B
for x in range (0, row): 
  newlist.append([])

  for y in range(0, col):
    newlist[x].append('R' + str(x) + 'C' + str(y))

print(newlist)
Answer from Sefe on Stack Overflow
Top answer
1 of 2
52

Starting from Pandas 0.25.0, there is internal method DataFrame.explode(), which was designed just for that:

res = df.explode("b")

output

In [98]: res
Out[98]:
   a  b
0  1  1
0  1  2
1  2  2
1  2  3
1  2  4
2  3  5

Solution for Pandas versions < 0.25: generic vectorized approach - will work also for multiple columns DFs:

assuming we have the following DF:

In [159]: df
Out[159]:
   a          b  c
0  1     [1, 2]  5
1  2  [2, 3, 4]  6
2  3        [5]  7

Solution:

In [160]: lst_col = 'b'

In [161]: pd.DataFrame({
     ...:     col:np.repeat(df[col].values, df[lst_col].str.len())
     ...:     for col in df.columns.difference([lst_col])
     ...: }).assign(**{lst_col:np.concatenate(df[lst_col].values)})[df.columns.tolist()]
     ...:
Out[161]:
   a  b  c
0  1  1  5
1  1  2  5
2  2  2  6
3  2  3  6
4  2  4  6
5  3  5  7

Setup:

df = pd.DataFrame({
    "a" : [1,2,3],
    "b" : [[1,2],[2,3,4],[5]],
    "c" : [5,6,7]
})

Vectorized NumPy approach:

In [124]: pd.DataFrame({'a':np.repeat(df.a.values, df.b.str.len()),
                        'b':np.concatenate(df.b.values)})
Out[124]:
   a  b
0  1  1
1  1  2
2  2  2
3  2  3
4  2  4
5  3  5

OLD answer:

Try this:

In [89]: df.set_index('a', append=True).b.apply(pd.Series).stack().reset_index(level=[0, 2], drop=True).reset_index()
Out[89]:
   a    0
0  1  1.0
1  1  2.0
2  2  2.0
3  2  3.0
4  2  4.0
5  3  5.0

Or bit nicer solution provided by @Boud:

In [110]: df.set_index('a').b.apply(pd.Series).stack().reset_index(level=-1, drop=True).astype(int).reset_index()
Out[110]:
   a  0
0  1  1
1  1  2
2  2  2
3  2  3
4  2  4
5  3  5
2 of 2
1

Here is another approach with itertuples -

df = pd.DataFrame({"a" : [1,2,3], "b" : [[1,2],[2,3,4],[5]]})

data = []

for i in df.itertuples():
    lst = i[2]
    for col2 in lst:
        data.append([i[1], col2])

df_output = pd.DataFrame(data =data, columns=df.columns)
df_output 

Output is -

        a   b
    0   1   1
    1   1   2
    2   2   2
    3   2   3
    4   2   4
    5   3   5

Edit: You can also compress the loops into a single code and populate data as -

data = [[i[1], col2] for i in df.itertuples() for col2 in i[2]]
Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 68196724 โ€บ make-a-dataframe-consisting-of-multiple-lists-as-rows-python
Make a dataframe consisting of multiple lists as rows, Python - Stack Overflow
I want to make a dataframe consisting of the lists below as rows. Does someone know how to do this quickly without manually making a dict first? Thank you! The elements in the list are floats. p000...
๐ŸŒ
Medium
ianh6ll6n.medium.com โ€บ expanding-a-pandas-list-column-to-rows-41c69aaf9488
Expanding a pandas list column to rows | by Ian Hellen | Medium
March 19, 2021 - We use pipelines in the MSTICPy Python package to automate multiple operations on DataFrames. You can read more about how we use pipelines in the MSTICPy documentation on pivot functions. If we were to try to use this pipeline with an input DataFrame with IP address lists instead of individual values, the WhoIs lookup (second line of the pipeline above) would not work and our pipeline would fail. Iโ€™ve seen a couple of answers to splitting lists into rows ...
๐ŸŒ
Medium
medium.com โ€บ @akaivdo โ€บ pandas-how-to-convert-a-multi-value-column-to-multiple-rows-75c8d4cc2f4a
Pandas >> How to Convert a Multi-Value Column to Multiple Rows | by NextGenTechDawn | Medium
April 12, 2022 - You can use explode() method of Pandas to convert a column with list-type values to multiple rows with other columns that are duplicated.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-rows-with-all-list-elements
Python โ€“ Rows with all List elements | GeeksforGeeks
May 1, 2023 - Append the current row to the res list if all the elements of sub_list are present in the current row. Return the res list as the result. ... # Python3 code to demonstrate working of # Rows with all List elements # Using set intersection # initializing list test_list = [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]] # printing original list print("The original list is : " + str(test_list)) # initializing list sub_list = [1, 2] sub_set = set(sub_list) # initializing result list res = [] # iterating through each row of test_list for row in test_list: # converting the row to a set row_set = set(row) # taking the intersection of row_set and sub_set intersection = row_set & sub_set # if all elements of sub_list are present in the row, append the row to res if len(intersection) == len(sub_set): res.append(row) # printing result print("Rows with list elements : " + str(res))
๐ŸŒ
Esri Community
community.esri.com โ€บ t5 โ€บ python-questions โ€บ list-of-unique-values-in-multiple-columns โ€บ td-p โ€บ 1024708
Solved: List of unique values in multiple columns - Esri Community
February 9, 2021 - import arcpy fc = "C:/path/to/data.gdb/FeatureClass" # Using a list of lists approach with arcpy.da.SearchCursor(fc, ["StartSuvey", "EndSurvey"]) as scur: # Use a list comprehension to pull the data out of the cusror date_info_list = [[row[0], row[1]] for row in scur] for date_list in date_info_list: print("Start: {}, End: {}".format(date_list[0], date_list[1])) # Using a list of dictionaries approach with arcpy.da.SearchCursor(fc, ["StartSuvey", "EndSurvey"]) as scur: # Use a list comprehension to pull the data out of the cusror date_info_list = [{"start": row[0], "end": row[1]} for row in scur] for date_dict in date_info_list: print("Start: {}, End: {}".date_dict["start"], date_dict["end"])
๐ŸŒ
Skytowner
skytowner.com โ€บ explore โ€บ splitting_column_of_lists_into_multiple_columns_in_pandas
Splitting column of lists into multiple columns in Pandas
To split a column, which contains lists, into multiple columns, use pd.concat([df, df["A"].apply(pd.Series)], axis=1).
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 23996344 โ€บ arrange-a-list-of-multiple-columns-into-a-matrix-in-python
text processing - Arrange a list of multiple columns into a matrix in Python - Stack Overflow
# Get all numbers and sort. for row in block_1: all_numbers.extend(row) for row in block_2: all_numbers.extend(row) all_numbers.sort() # Build the matrix. matrix = [] for i in range(0, len(all_numbers), rows): matrix.append(all_numbers[i:i+rows]) # Set the correct place for collumns. for i in range(len(matrix[0])): r = [] for j in range(len(matrix)): r.append(matrix[j][i]) new_block.append(r) print(new_block) ... Sign up to request clarification or add additional context in comments. ... with open('file1.txt','r') as data1: a=data1.readlines() with open('file2.txt','r') as data2: b=data2.readlines() # if list just intialize them to a,b with open('output.txt','a') as out: for i,j in zip(a,b): out.write(i+" "+j)