Issue
I have a data frame where I have a column named B which has apples and oranges as the data. How can I basically transform these values as separate columns in the same data frame.
Below is my code-
s={'A':[1,1,2,2],'B':['Apples','Oranges','Apples',"Oranges"],'C':[2014,2014,2016,2016],'value':[2,3,4,5]}
p=pd.DataFrame(data=s)
The O/p should be column with A, Apples, Oranges, C
How can I get this requirement done?
Solution
import pandas as pd
s={'A':[1,1,2,2],'B':['Apples','Oranges','Apples',"Oranges"],'C':[2014,2014,2016,2016],'value':[2,3,4,5]}
p=pd.DataFrame(data=s)
frames = []
for u, v in p.groupby("B"):
frames.append(v.rename(columns={"value": u}).drop(columns=["B"]))
pd.merge(frames[0], frames[1], how="inner", left_on=["A", "C"], right_on=["A", "C"])
results in
This assumes, that A
is some kind of "index" and that the values in C
are the same across the rows.
Answered By - Michael Kopp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.