0

I have a data set like this

data = {'Name': ['Ron','Charlie','Harry','Hermione','Luna','Hagrid','Draco']}
kdf = pd.DataFrame(data)

After this I add a column to my data frame as

kdf['x'] = 0

Now I want to fill the column x with 1's in specific places according to the list below

ls = [True, True , False, True, False, False, False]

For example I want 1's to be in Ron,Charlie and Hermione's row for that I wrote the below code

for i in ls:
    if i:
        kdf['x'] = 1
        print(i)
    else:
        kdf['x'] = 0

But the data set after this modification had 0's in all rows of column x, if I change 0 to 2 in else statement all rows in column x has 2, if I remove else statement complete all rows of column x have 1's in them

I don't understand why is this happening I also added print(i) in if statement to see if all of them are somehow understood as True but print(i) returns 3 True's so that seems okay.

I was expecting to my data frame to be modified such that could x has 1's in 1st, 2nd and 4th row but I am getting 1's in all rows of column x;if I change 0 to 2 in else statement all rows in column x has 2, if I remove else statement complete all rows of column x have 1's in them;I also added print(i) in if statement to see if all of them are somehow understood as True but print(i) returns 3 True's so that seems okay.

Edit: Someone suggested me this link Pandas conditional creation of a series/dataframe column and this is great I appreciate it but I want to understand what is the problem with my code not working in desired way.

Noob
  • 21
  • 2
  • `kdf['x'] = np.where(ls, 1, 0)` – mozway Jan 03 '23 at 12:19
  • I am voting against reopening your question, however the question in your edit is legitimate. When you do `kdf['x'] = N` you set the whole column to `N`, I recommend you go through the [Indexing and Selecting Data section of the pandas documentation](https://pandas.pydata.org/docs/user_guide/indexing.html) – ljmc Jan 05 '23 at 22:41

0 Answers0