简体   繁体   中英

Replace values of a Pandas dataframe's Column based on values of another column

Current Pandas Dataframe:

   Chunk_Num |reading_id |imei
   ____________________________________
0    0          4       35475624
1    0          6       35475624
2    0          6       35475624
3    0          7       35475624
4    0          7       35475624
5    0          11      35475624

I need to group every 2 Indexes into 1 Chunk_Num.

That is:

1) assign rows at index 0,1 to Chunk_Num=0

2) assign rows at index 2,3 to Chunk_Num=1

3) assign rows at index 4,5 to Chunk_Num=2

Needed o/p:

   Chunk_Num |reading_id |imei
   ____________________________________
0    0          4       35475624
1    0          6       35475624
2    1          6       35475624
3    1          7       35475624
4    2          7       35475624
5    2          11      35475624

Right now, I have:

index_list= [0,1,2,3,4,5]
chunk_list_elements=[0,1,2]

for i , c in zip(index_list, chunk_list_elements): # 3rd el of chunk_list, is mapped to 3rd el of index_list.
    transition2_df.loc[i,'Chunk_Num']= c
    transition2_df.loc[i+1,'Chunk_Num']= c
    i= i+2
display(transition2_df)

And that gives me:

   Chunk_Num |reading_id |imei
   ____________________________________
0    0          4       35475624
1    1          6       35475624
2    2          6       35475624
3    2          7       35475624
4    0          7       35475624
5    0          11      35475624

I'm not sure what I'm missing here. I'm open to other approaches as well besides using zip() .

Please help.

Use:

df['Chunk_Num'] = df.index // 2

Or

df['Chunk_num'] = (df.index.notna().cumsum()-1)//2

Output:

   Chunk_Num  reading_id      imei
0          0           4  35475624
1          0           6  35475624
2          1           6  35475624
3          1           7  35475624
4          2           7  35475624
5          2          11  35475624

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM