How to create a pivot table from this table (revised)
2 views (last 30 days)
Show older comments
Suppose I have a table T
locationgender
-----------------------------------------------------------
客户1NYmale
客户2LAfemale
客户3Austinfemale
客户4LAfemale
Then I want to create a pivot table
MaleFemale
--------------------------------------------
NY10
LA02
Austin01
I checked unstack and grpstat but I am not sure. What will be a next step?
0 Comments
Accepted Answer
Dave B
on 15 Aug 2021
Edited:Dave B
on 15 Aug 2021
Maybe there's a simpler path, but how about using
groupsummary
followed by
unstack
?
% Generate your table
cust = {'Customer 1' 'Customer 2' 'Customer 3'};
location = categorical({'NY' 'LA' 'Austin'},{'NY' 'LA' 'Austin'})';
gender = categorical({'male' 'female' 'female'},{'male' 'female'})';
t=table(location,gender);
% groupsumamry for counts, unstack for pivot, and then set NaNs to 0
s=groupsummary(t,{'location' 'gender'});
result=unstack(s,'GroupCount','gender');
result.female(isnan(result.female))=0;
result.male(isnan(result.male))=0;
disp(result)
0 Comments
More Answers (1)
the cyclist
on 15 Aug 2021
What you want to do is not really a pivot:
% Create your table
customer = {'1';'2';'3'};
位置= {'NY';'LA';'Austin'};
gender = {'male';'female';'female'};
tbl = table(customer,location,gender)
% You don't need the above. It is just to create your data.
% Create columns for male and female
tbl.male = double(strcmp(tbl.gender,'male'));
tbl.female = double(strcmp(tbl.gender,'female'));
% Drop the gender column
tbl.gender = []
See Also
Categories
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!