1

MY CODE:

df=pd.DataFrame(columns=["a","b"], index=np.arange(1,3))
for col in df.columns:
  df[col].values[:]=[[]*2]
print(df)
for col,n in enumerate(df.columns):
  for row in range(1,3):
    df[n][row].append([1,2,3])
    print(df)

OUTPUT:

           a   b
1  []  []
2  []  []
0 a
             a   b
1  [[1, 2, 3]]  []
2  [[1, 2, 3]]  []
0 a
                        a   b
1  [[1, 2, 3], [1, 2, 3]]  []
2  [[1, 2, 3], [1, 2, 3]]  []
1 b
                        a            b
1  [[1, 2, 3], [1, 2, 3]]  [[1, 2, 3]]
2  [[1, 2, 3], [1, 2, 3]]  [[1, 2, 3]]
1 b
                        a                       b
1  [[1, 2, 3], [1, 2, 3]]  [[1, 2, 3], [1, 2, 3]]
2  [[1, 2, 3], [1, 2, 3]]  [[1, 2, 3], [1, 2, 3]]
   

I want output as the list added to all the cells. But instead the list being added to a cell, it is being added to each row of the column. Please help. Thank you in advance.

Suggested output:

    a       b
1   []     []
2   []     []
0 a
         a    b
1   [[1,2,3]] []
2       []    []
0 a
         a    b
1   [[1,2,3]] []
2   [[1,2,3]] []
1 b
         a         b
1   [[1,2,3]]  [[1,2,3]]
2   [[1,2,3]]  []
1 b
         a         b
1   [[1,2,3]]  [[1,2,3]]
2   [[1,2,3]]  [[1,2,3]]
2
  • can you show the expected output Commented Jul 6, 2020 at 1:27
  • I have edited the question including suggested output. Please have a look. Thank you. Commented Jul 6, 2020 at 2:15

1 Answer 1

1

In Python, doing [[] * 2] doesn't actually produce [[],[]] as you probably expected, but [[]]. When you do df[col].values[:] = [[]*2] you are actually setting all rows in the column col to the same list. You can check this like so:

df = pd.DataFrame(columns=["a","b"], index=np.arange(1,3))
df["a"].values[:] = [[] * 2]
df["a"][1].append([1,2,3])
print(df)

After doing above operation the df would become like below, since you are actually modifying both rows at once:

             a    b
1  [[1, 2, 3]]  NaN
2  [[1, 2, 3]]  NaN

What you want to do is this:

for col in df.columns:
    for row in df.index:
        df[col][row] = []

Then

for col in df.columns:
    for row in df.index:
        df[col][row].append([1,2,3])
        print(df)

(Also notice how I don't use enumerate(df.columns) because we don't need it, and replaced range(1,3) with df.index.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.