Reputation: 565
I want to search through a column until I find the str Linear
, find the index of this location, add 1 to it and then extract a dataframe via slicing.
I have tried the following
for sheet_name, df in Input_Data.items():
for line in sheet_name:
if line.startswith('Linear'):
index = line.index('Linear')
break
df1 = df[index+1:236]
df1.loc[:,'Unnamed: 26']*=-1
df1.loc[:,'Unnamed: 27']*=-1
df=df1.sort_index(ascending=False)
Indexer=df.columns.tolist()
df = [(pd.concat([df[Indexer[0]],df[Indexer[num]]],axis=1)) for num in [1,2,3,4,5,6]]#concatenation
df = [(df[num].astype(str).agg(','.join, axis=1)) for num in [0,1,2,3,4,5]]
df=pd.DataFrame(df)
df=df.loc[0].append(df.loc[1].append(df.loc[2].append(df.loc[3].append(df.loc[4].append(df.loc[5])))))
However my 'index' is returning 0 where in fact it should be 125....
Upvotes: 0
Views: 571
Reputation: 41519
If line.startswith('Linear')
, 'Linear' will be the first word in line
.
If what you want is the line number, you can try finding it; enumerate
is your friend.
def find_index_of(lines, predicate):
for index, line in enumerate(lines):
if predicate(line):
return index
index = find_index_of(sheetname, lambda x: x.startswith("Linear"))
Upvotes: 1
Reputation: 628
The first check you do it startswith
, meaning the string begins with the argument - index 0 and forward, so index
will always be 0 in that case.
I think the loop you're looking for is with a range, or index number, to find the line that starts with that string, and refer to all the lines after that line.
for index in range(len(sheet_name)):
if sheet_name[index].startswith('Linear'):
df1 = df[index+1:236]
break
Upvotes: 0