python fix errors read a DF with text 1. transform each text to list with…
- User
python
fix errors
read a DF with text
-
transform each text to list with df['ngramm_list'] = ngrammsbase['ngramm'] .str.split(' |,')
-
filter DF where
1st word from ngramm_list = 1st word from name_list in each row
import pandas as pd
Sample data
data = { 'ngramm': ['tv mi', 'tv' , '1'], 'name': [ 'tv 4s телевизо led xiaomi mi', 'tv 4s', '2 3 4 ' ] }
df = pd.DataFrame(data)
Step 1: Transform each text to a list
df['ngramm_list'] = df['ngramm'] .str.split(' |,') df['name_list'] = df['name'] .str.split(' |,')
Step 2: Filter the DataFrame for each row
filtered_df = df.copy() # Create a copy of the original DataFrame
for index, row in df.iterrows(): name_list = row['name'] ngramm_first_word = row['ngramm_list'][0] if len(row['ngramm_list']) > 0 else None
# Check if the first word of ngramm_list is in the first element of name_list if ngramm_first_word in name_list[0]: filtered_df.loc[index, 'ngramm_list'] = ngramm_first_word else: filtered_df.loc[index, 'ngramm_list'] = Nonedisplay(filtered_df)
-
- Assistant
The provided code has some logic errors and misuses variables, especially within the loop for filtering the DataFrame. Let's correct these mistakes step by step:
- During the iteration,
name_listshould extract the list of words (which you've done asrow['name_list']instead ofrow['name']). - The filtering logic in the loop should set the entire row to
Nonewhen the condition is not met, but currently, the code only sets the cell to .
- During the iteration,
- User
use primary data as DF of strings
Sample data
data = { 'ngramm': ['tv mi', 'tv' , '1'], 'name': [ 'tv 4s телевизо led xiaomi mi', 'tv 4s', '2 3 4 ' ] }
df = pd.DataFrame(data)
- Assistant
Sure, I can show you how to perform the same operations directly with a DataFrame created from your sample data, without creating additional columns. Here's how you can achieve that:
import pandas as pd # Sample data data = { 'ngramm': ['tv mi', 'tv' , '1'], 'name': ['tv 4s телевизо led xiaomi mi', 'tv 4s', '2 3 4 '] } # Create the DataFrame df = pd.DataFrame(data) # Function to determine if the first word in one column matches the first word in another def match_first_word(row): ngramm_list = row['ngramm'].split(' ') name_list = row['name'].split(' ') ngramm_first_word = ngramm_list[0] if len(ngramm_list) > 0 else None name_first_word = name_list[0] if len(name_list) > 0 else None return ngramm_first_word == name_first_word # Filter the DataFrame filtered_df = df[df.apply(match_first_word, axis=1)] # Display the filtered DataFrame print(filtered_df)Explanation: