Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

python - Modifying dataFrames inside a list is not working

I have two DataFrames and I want to perform the same list of cleaning ops. I realized I can merge into one, and to everything in one pass, but I am still curios why this method is not working

test_1 = pd.DataFrame({
    "A": [1, 8, 5, 6, 0],
    "B": [15, 49, 34, 44, 63]
})
test_2 = pd.DataFrame({
    "A": [np.nan, 3, 6, 4, 9, 0],
    "B": [-100, 100, 200, 300, 400, 500]
})

Let's assume I want to only take the raws without NaNs: I tried

for df in [test_1, test_2]:
    df = df[pd.notnull(df["A"])]

but test_2 is left untouched. On the other hand if I do:

test_2 = test_2[pd.notnull(test_2["A"])]

Now I the first raw went away.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All these slicing/indexing operations create views/copies of the original dataframe and you then reassign df to these views/copies, meaning the originals are not touched at all.

Option 1
dropna(...inplace=True)
Try an in-place dropna call, this should modify the original object in-place

df_list = [test_1, test_2]
for df in df_list:
    df.dropna(subset=['A'], inplace=True)  

Note, this is one of the few times that I will ever recommend an in-place modification, because of this use case in particular.


Option 2
enumerate with reassignment
Alternatively, you may re-assign to the list -

for i, df in enumerate(df_list):
    df_list[i] = df.dropna(subset=['A'])  # df_list[i] = df[df.A.notnull()]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...