Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I modify DataFrame in place by selecting some columns when iterating through list of DataFrames?

dfl = [pd.DataFrame(
     {
        "A": 1.0,
        "B": pd.Timestamp("20130102"),
         "C": pd.Series(1, index=list(range(4)), dtype="float32"),
         "D": "foo",
     }
)]
for df in dfl:
  df = df[["A", "B"]]
print(dfl)

I was expecting the output has only column "A" and "B" since I was modifying the DataFrame in place (df = ...). However I got:

[     A          B    C    D
0  1.0 2013-01-02  1.0  foo
1  1.0 2013-01-02  1.0  foo
2  1.0 2013-01-02  1.0  foo
3  1.0 2013-01-02  1.0  foo]

What is the reason and how can I select (not drop) some columns from the each DataFrame in that list in place?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because df is a local pointer to the loop. By doing df = df[['A','B']], you tell the pointer to point to something new, which doesn’t override the existing element of the list. Another similar example:

ll = [[1]]
for l in ll:
    l = None
print(ll)
# output: [[1]]

To override the element, you would want to do:

for i, d in enumerate(dfl):
    dfl[i] = d[['A','B']]

print(dfl)

Out:

[     A          B
0  1.0 2013-01-02
1  1.0 2013-01-02
2  1.0 2013-01-02
3  1.0 2013-01-02]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading