pythonsmartsheet-apismartsheet-api-2.0

How to concatenate cell values from multiple columns into a single column?


Note: I have found a partial solution to my problem, please refer to the UPDATE section below.

I am currently trying to take data from 3 separate columns and merge them together into another specified column. For clarity please refer to the image below, where code 1, code 2, and code 3 are all concatenated together in the Merged Code column. Example of desired outcome. I have written a for loop that can update the values of every cell in a specified column, please refer to the code below.

for rows in row_id:
# Build new cell value
new_cell = smartsheet.models.Cell()
new_cell.column_id = column_id_final  # column id of previously created column
    # A for loop to fill in the rows with information from other rows
    for rows in row_id:
        new_cell.value = smart.Sheets.get_sheet(1174866712913796)
        new_cell.strict = False

In the new_cell.value portion of the second loop I could simply enter a string 'value' which would then fill in all the rows of the specified column (column_id_final) with 'value'. My thought process from here is to then work on being able to print off all of the display values from a given row. Given that if I could do this I could simply just concatenate the three variables that each contained all the display values from a given column. Refer to the code below to see my attempt of this.

# For loops to extract display values from each cell in a given column
cell_id = ''
row_info = ''
# Get all of the information stored within the rows of a sheet
for row in sheet.rows:
    row_info += str(smart.Sheets.get_row(1174866712913796, row.id))
print(row_info)
# pull the display value from each component of the row_info variable
for cell in row_info.cell:
    cell_id += string(cell.display_value) #is there a display value property?
print(cell_id)

The issue I run into is how to display the values of all the cells in a specified column. Is there a way I can do this?

UPDATE

Thanks to Emi's comment I looked into Pandas and found a partial solution to my problem. I am now able to concatenate the columns I want into a single column, upload this column to smartsheet, and move the rows to another sheet. However, when I move the rows it posts them to the bottom of the destination sheet. I know this is the default position, but I do not know if there are location attributes for the move rows function. Refer to the code below to get a better understanding of my process.

def add_merged_column():
    sheet = smart.Sheets.get_sheet(1174866712913796)  # store sheet information in sheet variable
    col_names = [col.title for col in
                 sheet.columns]  # Define column names for data fram as being equal to the column titles in the sheet information variable
    rows = []  # define rows
    for row in sheet.rows:  # for loop to iterate through the rows of 'sheet' and create a cell list for each
        cells = []  # define cells
        for cell in row.cells:  # for each cell within every row append the updated cell value
            cells.append(cell.value)
        rows.append(cells)
    df = pd.DataFrame(rows, columns=col_names)  # create data frame using panda, define columns
    df = df.set_index('Unique ID')  # get rid of built in index, make desired merged column index
    df['Unique ID'] = df['Column 1'].map(str) + ' ' + df['Column 2'].map(str) + ' ' + df['Column 3'].map(
        str)  # concatenate the desired columns into a single column
    merged_data = df['Unique ID']  # assign a variable name to result
    merged_data.to_csv(_dir + '\excel\proc_data.csv')  # send merged_data to a csv file and specify file path
    print(merged_data)
    result = smart.Sheets.import_csv_sheet(_dir + '\Excel\proc_data.csv', header_row_index=0)  #  import newly saved csv file into smartsheet

    sheet_csv = smart.Sheets.get_sheet(result.data.id)

    ################################################################################################################

    # iterate through the rows array and build comma-delimited list of row ids
    row_ids = ''  # define row_id
    for row in sheet_csv.rows:
        row_ids += str(
            row.id) + ', '  # the += adds to the existing variable each iteration, rather than defining an entirely new variable, this is what allows it to be a list, hence the addition of the ','
        # x += y is the same as x = x.__iadd__(y)

    # remove the final (excess) comma and space from the end of the row_ids string
    row_ids = row_ids[
              :len(row_ids) - 2]  # Specifies that row_ids is not equal to row_ids from index 0 -> length of the ids - 2

    row_ids = list(map(int, row_ids.split(',')))

    response = smart.Sheets.move_rows(result.data.id, smart.models.CopyOrMoveRowDirective(
        {'row_ids': row_ids, 'to': smart.models.CopyOrMoveRowDestination({'sheet_id': 1174866712913796})}))

    return merged_data

Solution

  • Could you use a pandas dataframe for your data? I've created a sample dataframe of your data (df), but you could pull it in from csv? I'm not sure how you're storing your data.

    df = pd.DataFrame({'code 1':[423, 456], 'code 2':[657, 243], 'code 3':[568, 987]})
    

    Then you can just convert the numbers to strings, and join them together like so:

    df = df.astype(str)
    df['Merged Code'] = df['code 1'] + ' ' + df['code 2'] + ' ' + df['code 3']