let’s say I have the below dataframe:
JavaScript
x
3
1
dataframe = pd.DataFrame({'col1': ['Name', 'Location', 'Phone','Name', 'Location'],
2
'Values': ['Mark', 'New York', '656','John', 'Boston']})
3
which looks like this:
JavaScript
1
7
1
col1 Values
2
Name Mark
3
Location New York
4
Phone 656
5
Name John
6
Location Boston
7
As you can see I have my wanted columns as rows in col1 and not all values have a Phone number, is there a way for me to transform this dataframe to look like this:
JavaScript
1
4
1
Name Location Phone
2
Mark New York 656
3
John Boston NaN
4
I have tried to transpose in Excel, do a Pivot and a Pivot_Table:
JavaScript
1
2
1
pivoted = pd.pivot_table(data = dataframe, values='Values', columns='col1')
2
But this comes out incorrectly. any help would be appreciated on this.
NOTES: All new section start with the Name value and end before the Name value of the next person.
Advertisement
Answer
Create a new index
using cumsum
to identify unique sections then do pivot
as usual…
JavaScript
1
3
1
df['index'] = df['col1'].eq('Name').cumsum()
2
df.pivot('index', 'col1', 'Values')
3
JavaScript
1
5
1
col1 Location Name Phone
2
index
3
1 New York Mark 656
4
2 Boston John NaN
5