Python Forum
Assigning Column nunique values to another DataFrame column
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Assigning Column nunique values to another DataFrame column
#1
I'm having issues assigning an nunique value to a dataframe column.

Can't show real data but dataframe df is like below:

Doc_Set     Doc_Num    Status
     
Set_123     ED-0001    Complete
Set_123     EG-0002    Complete
Set_123     EG-0002    Complete 
Set_456     EN-0010    In Progress
Set_456     EN-0010    In Progress
Set_789     ED-0500    Complete
I need another dataframe 'df2' with unique Doc_Set values and number of unique Doc_Num values for each, where Status = Complete. So df2 should look like:

Doc_Set     Docs_Unique    
     
Set_123         2  
Set_789         1
I'm doing the following:

df2['Doc_Set'] = df[df['Status'] == 'Complete'].Doc_Set.unique()
 
for d in df2['Doc_Set']:
df2['Docs_Unique'] = df[df['Doc_Set']==d].Doc_Num.nunique()
Somehow every row in df2['Docs_Unique'] ends up as '5'.
Although, if I print(df[df['Doc_Set']==d].Doc_Num.nunique()) in the for loop, I get correct values.

What am I doing wrong?
Reply
#2
Hey , I guess you should use group by, if you had provided a sample of dataset, I could have tried it out first, but anyways i guess this should work.
df2.groupby('Doc_Set').nunique()
Also here is a pandas guide if you don't know how groupby works Pandas
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Adding PD DataFrame column bsben 2 245 Mar-08-2024, 10:46 PM
Last Post: deanhystad
  Get an average of the unique values of a column with group by condition and assign it klllmmm 0 223 Feb-17-2024, 05:53 PM
Last Post: klllmmm
  Help copying a column from a csv to another file with some extras g0nz0uk 3 403 Feb-01-2024, 03:12 PM
Last Post: DeaD_EyE
  Converting column of values into muliple columns of counts highland44 0 205 Feb-01-2024, 12:48 AM
Last Post: highland44
  Python code to set column width 1418 11 945 Jan-20-2024, 07:20 AM
Last Post: Pedroski55
  Python Alteryx QS-Passing pandas dataframe column inside SQL query where condition sanky1990 0 690 Dec-04-2023, 09:48 PM
Last Post: sanky1990
  Returning Column and Row Data From Spreadsheet knight2000 0 413 Oct-22-2023, 07:07 AM
Last Post: knight2000
  Find a string from a column of one table in another table visedwings049 8 1,085 Sep-07-2023, 03:22 PM
Last Post: deanhystad
  DF value by Column... not sure what to call it tester_V 2 533 Aug-26-2023, 06:56 PM
Last Post: tester_V
  python sqlite autoincrement in primary column janeik 6 1,075 Aug-13-2023, 11:22 AM
Last Post: janeik

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020