Find a series in dataframe and replace it with original row

让人想犯罪 __ 提交于 2020-06-29 03:47:15

问题


I have below dataframe df but some D4s with True was causing an issue in my custom ordering. Temporarily, I stored such rows in a list and turned those D4 values to False intentionally and sorted with my custom ordering.

Index D1  D2  D3   D4      D5
    0   8   5   0  False   True
    1  45  35   0   True  False
    2  35  10   1  False   True
    3  40   5   0   True  False
    4  12  10   5  False  False
    5  18  15  13  False   True
    6  25  15   5   True  False
    7  35  10  11  False   True
    8  95  50   0  False  False

hacked_rows = []
def hack_d4(row):
    if row['D3'] in [0, 1]:
       row['D4'] = False
       hacked_rows.append(row)
    return row
df = df.apply(lambda x: hack_d4(x), axis=1)
ordered_df = order_df(df) 

Ordered df with custom ordering, It does not change the df rows but has few new columns and the row has all the previous columns as is, only order has changed a bit.

Now I am done with custom ordering. Now I want to revert hacked_rows back to the original dataframe which are there on the list. but not sure how to replace them back.

I tried below code for one row, but no luck, its throwing TypeError:

item = hacked_rows[0]
item = item.drop('D3')
ordered_df.loc[item]    # But this line is throwing error.

@cs95 - Your answerhelped me a little, but it did not completely solve the problem. The tricky point is how to update back hacked_rows to the ordered_df without hampering the ordering. Can you help in there?

Note- I am okay if anyone can suggest a different approach to replace the True values temporarily.

来源:https://stackoverflow.com/questions/62593478/find-a-series-in-dataframe-and-replace-it-with-original-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!