Reputation: 849
I want to search the specific words are present in the dataframe. If word is present in the dataframe, need to export the subset of dataframe in to Excel. Here problem is every time it is calling columns names. Column names are same for all dataframes.
df = pd.DataFrame({
'Name': ['Ann', 'Juh', 'Jeo', 'Sam'],
'Age': [43,29,42,59],
'Task1': ['Drafting a letter', 'Sending', 'Pasting', 'Sending'],
'Task2': ['Sending', 'Paking', 'Sending', 'Pasting'],
'Task3': ['Packing', 'Letter Drafting', 'Paking', 'Letter Drafting']
})
writer = pd.ExcelWriter("C:..\\pp.xlsx", engine='xlsxwriter')
row = 0
b = ['Sending','paking']
for var in b: ----> # Here 'b' is searchable keywords.
lower_df = df.apply(lambda x: x.astype(str).str.lower())
margin = df[lower_df.iloc[:,3:5].astype(str).apply(lambda x: x.str.contains(var.lower())).any(axis=1)]
margin['search_term'] = var ---> #Create the column with search keyword
if len(margin) > 0: ---> #If no data found need to eliminate
margin.to_excel(writer,startrow=row)
row = row + len(margin.index) +1
writer.save()
If i use header=False
it removes the all the column names but I want keep the starting of dataframe.
Upvotes: 2
Views: 2050
Reputation: 863236
You can change logic - append each DataFrame to list dfs
and last concat
for final DataFrame
:
writer = pd.ExcelWriter("pp.xlsx", engine='xlsxwriter')
b = ['Sending','paking']
dfs = []
for var in b: # Here 'b' is searchable keywords.
lower_df = df.apply(lambda x: x.astype(str).str.lower())
mask = (lower_df.iloc[:,3:5]
.astype(str)
.apply(lambda x: x.str.contains(var.lower()))
.any(axis=1))
margin = df[mask].copy()
margin['search_term'] = var #Create the column with search keyword
#print (margin)
dfs.append(margin)
pd.concat(dfs).to_excel(writer, index=False)
writer.save()
Upvotes: 1