Hello,
to answer your first question:
Your values are a, b, c, d
= 12, 31, 16, 26
(four values thus four rows are expected). You want to find out if:
a
in row1
b
in row2
c
in row3
d
in row4
Note that you’re bypassing row 0
since panda dataframes begin with the standard starting convention of 0
. In your expected outcome you only listed three rows. Plus, the first row does not include any of the values that you have listed. I will interpret this as an oversight / typo(?).
To find the rows as per your requirements, you can try something like this:
import pandas as pd
# Raw data to make original dataframe
data1 = [1,3,23,16,15,18]
data2 = [3,2,31,36,4,8]
data3 = [8,12,32,7,78,2]
data4 = [8,54,1,56,26,88]
# Update dataframe with column titles and raw data
df1 = pd.DataFrame(({'Column 1': data1,
'Column 2': data2,
'Column 3': data3,
'Column 4': data4}))
df2 = pd.DataFrame()
print('\n', df1, '\n', end='', sep='') # print original dataframe for reference
a, b, c, d = 12, 31, 16, 26 # Values to search for
values = [a, b, c, d] # Put values in a list so that they may be indexed
# You can use for loops to index through the rows and through the required search values
for col in ('Column 1', 'Column 2', 'Column 3', 'Column 4'):
for j, value in enumerate(values):
if df1.loc[j+1, col] == value:
df2 = pd.concat([df2, df1[df1[col] == value]])
df3 = df2.sort_index()
print(df3)
This will provide this output:
Column 1 Column 2 Column 3 Column 4
1 3 2 12 54 # row 1, value 12
2 23 31 32 1 # row 2, value 31
3 16 36 7 56 # row 3, value 16
4 15 4 78 26 # row 4, value 26