Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

python - Is there any function in Pandas to unstack column values into separate columns with multiple identifying columns?

I have a data set like this - https://i.stack.imgur.com/J2qT4.png

Market LoanID Segment LoanTerm Field FieldValue Month
Aus AMID11 Sales 6 End AR 1 Jan
Aus AMID11 Sales 6 End AR 1 Feb
Aus AMID11 Sales 6 End AR 1 Mar
Aus AMID12 Marketing 12 End AR 0 Jan
Aus AMID12 Marketing 12 End AR 1 Feb
Aus AMID12 Marketing 12 End AR 1 Mar
Aus AMID11 Sales 6 IntRate 15.7% Jan
Aus AMID11 Sales 6 IntRate 16.7% Feb
Aus AMID11 Sales 6 IntRate 15.7% March
Aus AMID12 Marketing 12 IntRate - Jan
Aus AMID12 Marketing 12 IntRate 15.7% Feb
Aus AMID12 Marketing 12 IntRate 16.7% Mar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

there is a little bit changes between the desired output to what i got but i think it is due to data being incorrect ('mar' and 'march' , and 'feb' twice):

df = pd.read_csv(StringIO('''Market LoanID  Segment LoanTerm    Field   FieldValue  Month
Aus AMID11  Sales   6   End AR  1   Jan
Aus AMID11  Sales   6   End AR  1   Feb
Aus AMID11  Sales   6   End AR  1   Mar
Aus AMID12  Marketing   12  End AR  0   Jan
Aus AMID12  Marketing   12  End AR  1   Feb
Aus AMID12  Marketing   12  End AR  1   March
Aus AMID11  Sales   6   IntRate 15.7%   Jan
Aus AMID11  Sales   6   IntRate 16.7%   Feb
Aus AMID11  Sales   6   IntRate 15.7%   March
Aus AMID12  Marketing   12  IntRate -   Jan
Aus AMID12  Marketing   12  IntRate 15.7%   Feb
Aus AMID12  Marketing   12  IntRate 16.7%   Feb'''),sep='')
indexes= ['Market','LoanID','Segment','LoanTerm','Month']
pd.pivot_table(data=df,index=indexes,columns='Field',values='FieldValue',aggfunc='first').reset_index()

Output:

    Market  LoanID  Segment     LoanTerm    Month   End AR  IntRate
0   Aus     AMID11  Sales       6           Feb     1       16.7%
1   Aus     AMID11  Sales       6           Jan     1       15.7%
2   Aus     AMID11  Sales       6           Mar     1       NaN
3   Aus     AMID11  Sales       6           March   NaN     15.7%
4   Aus     AMID12  Marketing   12          Feb     1       15.7%
5   Aus     AMID12  Marketing   12          Jan     0       -
6   Aus     AMID12  Marketing   12          March   1       NaN

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...