Print Next Line In Pandas Dataframe
Solution 1:
You should first get the index of the row that matches the question by index
function of DataFrame. To get partial match to your question, use str.contains
.
df = pd.DataFrame({'data':
["(Row 1) Bot: Hi, What are your hobbies?",
"(Row 2) User1: Cricket, FootBall",
"(Row 3) Bot: Hi, What is your name?",
"(Row 4) User2: Alexa",
"(Row 5) Bot: Hi, What are your hobbies?",
"(Row 6) User3: Tennis, Baseball"]
})
idx = df[df['data'].str.contains("Hi, What are your hobbies?")].index.tolist()
for i in idx:
if i < len(df) - 1:
print(df.iloc[i + 1].values[0])
Output:
(Row2) User1: Cricket, FootBall
(Row6) User3: Tennis, Baseball
So, in the above code, idx
holds a list of indexes that match your query. In the last line, you print the values of the next row corresponding those indices.
Solution 2:
Using the Data Frame declaration from @CentAu
import pandas as pd
Chat_Column = pd.DataFrame({'data':
["(Row 1) Bot: Hi, What are your hobbies?",
"(Row 2) User1: Cricket, FootBall",
"(Row 3) Bot: Hi, What is your name?",
"(Row 4) User2: Alexa",
"(Row 5) Bot: Hi, What are your hobbies?",
"(Row 6) User3: Tennis, Baseball"]
})
for ndx, row in Chat_Column.iterrows():
if"Bot: Hi, What are your hobbies?"in row["data"]:
print(Chat_Column.iloc[ndx+1]["data"])
Solution 3:
d = {'a':['Question1','Answer1','Question2','Answer2','Question3','Answer3']}
df = pd.DataFrame(d)
printdf['a'].shift(-1)[df['a'] == 'Question2'].values[0]
But I would recommend putting the dataframe into two columns (Quesiton and Answer).
Point of note - using pandas native indexing will be considerably faster than iterating through a list of strings and testing if
statements on every iteration. That said, it is probably irrelevant if it is only a couple hundred / thousand lines, but could be obvious if the DataFrame increases in size.
Post a Comment for "Print Next Line In Pandas Dataframe"