Solution for Print a specific row and row+1 based on column value in Python Dataframe
is Given Below:
I have a python dataframe as shown below, I am trying to access rows based on value of column C. When Column C==1, I want to print the corresponding row and row+1 side by side as shown in expected output below. Please note when there are continuous 1’s it should print multiple pairs as shown below in expected result.
Expected Output Format:
1. F, M, 1; S, P, 3 2. a, c, 1; h, g, 1 3. h, g, 1; k, j, 2 4. q, b, 1; S, P, 1 5. S, P, 1; F, z, 1 6. F, z, 1; q, z, 1
I was trying to doing something like:
if (df['c'] == 1): print...
I see following error:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Please help me with some ideas to print the pattern described. Thanks in advance!!
The best way is to add columns with the next row’s values, and print just those line who fill the condition:
df['A_next'] = df['A'].shift(-1) df['B_next'] = df['B'].shift(-1) new_df = df[df['C'] == 1] print(new_df)