Reputation: 419
I have a dataframe with four columns. First column represents Subject, each Subject continuosly repeats 60 times in a column. In total there is 54 Subjects. Second columns represents the Block. Each Subject underwent over 6 Blocks, starting with 1st and ending with 6th. Third column is Name. Each Block contained 10 Names, which were chosen randomly from 20 possible Names. Fourth column represents Serial number of the Name. So each Block contained Serial number from 1-10 and corresponding randomly assigned Name. Problem is, names were assigned wrong to their Serial number.
What i want is to swap (change the position) Names based on corresponding Serial number. So the Name under Serial Number 1
would be swapped with Name with the Serial Number 6
(pattern: 1=6, 2=7, 3=8, 4=9, 5=10)
. Serial Number stay untouched, but the sequence of Name needs to be changed. I want to to this for each Block for each Subject. I have a code which is doing the right thing, but the problem is, it is only working for the first Subject:
df['Name'] = (df.assign(blk_5 = (np.arange(len(df))//5+1) % 2,
blk_10 = np.arange(len(df)) // 10
)
.sort_values(['Block','blk_10','blk_5'])
['Name'].values
)
I tried with groupby, to group the column Subject and assign function to each Subject, but unsuccessfull.
def function_test(df):
df['Name'] = (df.assign(blk_5 = (np.arange(len(df))//5+1) % 2,
blk_10 = np.arange(len(df)) // 10
)
.sort_values(['Block','blk_10','blk_5'])
['Name'].values
)
......
grouped = df.groupby('Subject')
print(grouped.transform(function_test))
...
Retrurns: AttributeError: 'Series' object has no attribute 'assign'
Another thing i tried:
test = df.groupby(['Subject', 'Block']).apply(function_test)
which does nothing!
Any suggestions? Thanks a lot!
Upvotes: 1
Views: 119
Reputation: 862611
IIUC use:
def function_test(x):
x['Name'] = (x.assign(blk_5 = (np.arange(len(x))//5+1) % 2,
blk_10 = np.arange(len(x)) // 10
)
.sort_values(['Block','blk_10','blk_5'])
['Name'].values
)
return x
df = df.groupby('Subject').apply(function_test)
Upvotes: 1