Reputation: 426
I have the following DataFrame:
type result
0 IP_1 ['a', 'b']
1 IP_2 ['c', 'd']
I want it reshaped to look like this:
IP_1 IP_2
0 ['a', 'b'] ['c', 'd']
but when I try df.pivot(columns='type', values='result')
I got:
IP_1 IP_2
0 Nan ['a', 'b']
1 ['c', 'd'] NaN
How can I solve that?
Upvotes: 0
Views: 89
Reputation: 23099
If i understand your correctly you need to create create a new index then unstack based the position of each unique type
value.
df.set_index([df.groupby("type").cumcount(), df["type"]])["result"].unstack()
type IP_1 IP_2
0 ['a', 'b'] ['c', 'd']
Upvotes: 1
Reputation: 2583
You should have an the same index for both:
df = pd.DataFrame([1,["IP_1","['a', 'b']"],[2,"IP_2","['c', 'd']"]],columns=['ind','type','result'])
print(df.pivot(columns=['type'],index='ind'))
result
type IP_1 IP_2
ind
1 ['a', 'b'] ['c', 'd']
Upvotes: 1
Reputation: 11917
Try transpose after changing index to type,
df.set_index("type").transpose().reset_index(drop=True)
type IP_1 IP_2
0 [a, b] [c, d]
Upvotes: 1
Reputation: 2484
I've done it with a transpose
df = pd.DataFrame([
{"type": "IP_1", "result": ['a', 'b']},
{"type": "IP_2", "result": ['c', 'd']},
])
df = df.set_index('type').T
Output:
type IP_1 IP_2
result [a, b] [c, d]
Upvotes: 3