I have a bit python code below. Just an example to show the problem: I would like to select some lines in a data frame basing on some values. Somehow this needs to be in a for loop, and I used .append() to add each selection of rows into a final file. But the result is not the same as what I expected. I learned by reading quite some posts that we should not append as a data frame in a loop. So I don't know how I could do this now. Could somebody help please? Thanks a lot!
import pandas as pd
df = pd.DataFrame({'a': [4, 5, 6, 7], 'b': [10, 20, 30, 40], 'c': [100, 50, -30, -50]})
df['diff'] = (df['b'] - df['c']).abs()
print(df)
df1 = df[df['diff'] == 90]
df2 = df[df['diff'] == 60]
list = [df1, df2]
def try_1(list):
output = []
for item in list:
output.append(item)
return output
print(try_1(list))
output from the code
a b c diff
0 4 10 100 90
1 5 20 50 30
2 6 30 -30 60
3 7 40 -50 90
[ a b c diff
0 4 10 100 90
3 7 40 -50 90, a b c diff
2 6 30 -30 60]
but the expected output of print(try_1(list))
a b c diff
4 10 100 90
7 40 -50 90
6 30 -30 60
Also, I need to write this final one into a file. I tried .write(), and it complained not a string. How could I solve this please? Thanks!