results=[] for row in tqdm(testdf.itertuples(), total=df.shape[0]): xq =…
- User
results=[] for row in tqdm(test_df.itertuples(), total=df.shape[0]): xq = encoder.encode(row.searchable, device=torch_device) # Search using the query vector D, I = gpu_index.search(xq.reshape(1, -1), k_nearest)
# Get recommended recommended_sme = df.iloc[I[0]]['id'].to_list() # Conver row back to df row = pd.DataFrame([row])i want to add recommendation_sme to row
- Assistant
To add the
recommended_smevalues to therowdataframe, you can use theassign()function from the pandas library. Here's an updated code snippet:results=[] for row in tqdm(test_df.itertuples(), total=df.shape[0]): xq = encoder.encode(row.searchable, device=torch_device) # Search using the query vector D, I = gpu_index.search(xq.reshape(1, -1), k_nearest) # Get recommended recommended_sme = df.iloc[I[0]]['id'].to_list() # Convert row back to df and add recommended_sme column row_df = pd.DataFrame([row]) row_df = row_df.assign(recommended_sme=recommended_sme) # Add row_df to results results.append(row_df)In this updated code, the
rowis first converted back to a dataframe calledrow_df. Then, theassign()function is used to add a new column namedrecommended_smewith the values of therecommended_smelist. Finally, therow_dfis added to theresultslist. - User
ValueError Traceback (most recent call last) Cell In[134], line 9 7 # Convert row back to df and add recommended_sme column 8 row_df = pd.DataFrame([row]) ----> 9 row_df = row_df.assign(recommended_sme=recommended_sme)
File /opt/conda/lib/python3.10/site-packages/pandas/core/frame.py:4852, in DataFrame.assign(self, **kwargs) 4849 data = self.copy(deep=None) 4851 for k, v in kwargs.items(): -> 4852 data[k] = com.apply_if_callable(v, data) 4853 return data
File /opt/conda/lib/python3.10/site-packages/pandas/core/frame.py:3959, in DataFrame.setitem(self, key, value) 3956 self._setitem_array([key], value) 3957 else: 3958 # set column -> 3959 self._set_item(key, value)
File /opt/conda/lib/python3.10/site-packages/pandas/core/frame.py:4152, in DataFrame._set_item(self, key, value) 4142 def _set_item(self, key, value) -> None: 4143 """ 4144 Add series to DataFrame in specified column. 4145 (...) ... 579 "does not match length of index " 580 f"({len(index)})" 581 )
ValueError: Length of values (10) does not match length of index (1)
- Assistant
Apologies for the mistake. It seems that there is a mismatch between the length of
recommended_smeand the length of the index inrow_df.To resolve this issue, you can either ensure that
recommended_smehas the same length as the index inrow_df, or you can modify the code to addrecommended_smeas a new column intest_dfinstead of creating a separate dataframe for each row. Here's an updated code snippet that addsrecommended_smeas a new column intest_df:results = [] for row in tqdm(test_df.itertuples(), total=df.shape[0]): xq = encoder.encode(row.searchable, device=torch_device) # Search using the query vector D, I = gpu_index.search(xq.reshape(1, -1), k_nearest) # Get recommended recommended_sme = df.iloc[I[0]]['id'].tolist() # Add recommended_sme as a new column in test_df test_df.loc[row.Index, 'recommended_sme'] = recommended_sme # Add row to results (optional) results.append(row)In this updated code, the values are added as a new column named in the dataframe using the indexer. Additionally, if you still need to store each row separately in the list, you can add to the list as before.
- User
KeyError Traceback (most recent call last) File /opt/conda/lib/python3.10/site-packages/pandas/core/indexes/base.py:3652, in Index.get_loc(self, key) 3651 try: -> 3652 return self._engine.get_loc(casted_key) 3653 except KeyError as err:
File /opt/conda/lib/python3.10/site-packages/pandas/_libs/index.pyx:147, in pandas._libs.index.IndexEngine.get_loc()
File /opt/conda/lib/python3.10/site-packages/pandas/_libs/index.pyx:176, in pandas._libs.index.IndexEngine.get_loc()
File pandas/_libs/hashtable_class_helper.pxi:7080, in pandas._libs.hashtable.PyObjectHashTable.get_item()
File pandas/_libs/hashtable_class_helper.pxi:7088, in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'recommended_sme'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last) File /opt/conda/lib/python3.10/site-packages/pandas/core/frame.py:4188, in DataFrame._set_value(self, index, col, value, takeable) 4187 else: -> 4188 icol = self.columns.get_loc(col) 4189 iindex = self.index.get_loc(index) ... 5734 # if key is not a scalar, directly raise an error (the code below 5735 # would convert to numpy arrays and raise later any way) - GH29926 -> 5736 raise InvalidIndexError(key)
- Assistant
Apologies for the confusion. The error is occurring because the
recommended_smecolumn is not present in thetest_dfdataframe, and when trying to access it usingtest_df.loc[row.Index, 'recommended_sme'], aKeyErroris raised.To resolve this issue, you can create an empty list to store the
recommended_smevalues and then add it as a new column intest_dfoutside the loop. Here's an updated code snippet:results = [] recommended_sme_list = [] for row in tqdm(test_df.itertuples(), total=test_df.shape[0]): xq = encoder.encode(row.searchable, device=torch_device) # Search using the query vector D, I = gpu_index.search(xq.reshape(1, -1), k_nearest) # Get recommended recommended_sme = df.iloc[I[0]]['id'].tolist() # Add recommended_sme to list recommended_sme_list.append(recommended_sme) # Add row to results (optional) results.append(row) # Add recommended_sme as a new column in test_df test_df['recommended_sme'] = recommended_sme_list - User
fix this: if row_df.member_id is in recommended_sme: print('yes')
recommended_sme is a list
- Assistant
To fix the issue and check if
row_df.member_idis in therecommended_smelist, you can modify the code as follows:if row_df.member_id.iloc[0] in recommended_sme: print('yes')In this code,
row_df.member_id.iloc[0]is used to access the value of themember_idcolumn inrow_df. We then use theinoperator to check if this value is in therecommended_smelist.Note that
recommended_smeshould be a list that contains the values you wish to comparerow_df.member_idagainst. - User
add a list as a cell value in a column of a df
- Assistant
To add a list as a cell value in a column of a DataFrame in pandas, you can use the
apply()function. Here is an example code snippet:import pandas as pd # Create a DataFrame df = pd.DataFrame({'Column1': [1, 2, 3]}) # Define a list to be added as a cell value my_list = [4, 5, 6] # Add the list as a cell value in a column df['Column2'] = df['Column1'].apply(lambda x: my_list if x == 2 else []) print(df)In this example, we first create a DataFrame
dfwith a columnColumn1. Next, we define a listmy_list. We then use theapply()function along with a lambda function to conditionally addmy_listas a cell value in a separate columnColumn2based on certain criteria. In the given example,my_listis added toColumn2when the value inColumn1is equal to 2. For all other rows, an empty list[]is added.The output will be:
Column1 Column2 0 1 [] 1 2 [4, 5, 6] 2 3 []In this output, you can see that the list is added as a cell value in Column2 for the row where Column1 equals 2, while empty lists are added for the other rows.