So I basically need my data to look like the one in the picture below. I've researched endlessly on this site and even created an account to see if anyone can help me. I'm sorry I don't even know how to properly explain the problem.
Asked
Active
Viewed 91 times
-2
-
This is called "pivoting" your data frame. See [`pandas.DataFrame.pivot`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html#pandas.DataFrame.pivot). – ForceBru Aug 11 '21 at 18:34
-
Does this answer your question? [How to pivot a dataframe in Pandas?](https://stackoverflow.com/questions/28337117/how-to-pivot-a-dataframe-in-pandas) – Tomerikoo Aug 11 '21 at 18:54
1 Answers
0
pandas is an incredibly useful library for dealing with data in a tabular format
Assuming you have that data available as either a list of dictionaries, or a dictionary of lists, you can easily create a pandas DataFrame from that data
In [31]: data = {'Client': ['Client 1', 'Client 1', 'Client 1', 'Client 2', 'Client 2', 'Client 2', 'Client 3', 'Client 3', 'Client 3'],
...: 'Ticker': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'],
...: 'PositionValue': [1000, 2000, 10000, 300, 6000, 10000, 45345, 546456, 456456]
...: }
In [32]: df = pd.DataFrame(data)
In [33]: df
Out[33]:
Client Ticker PositionValue
0 Client 1 A 1000
1 Client 1 B 2000
2 Client 1 C 10000
3 Client 2 A 300
4 Client 2 B 6000
5 Client 2 C 10000
6 Client 3 A 45345
7 Client 3 B 546456
8 Client 3 C 456456
You can then change the shape of that data by pivoting it, described in the User Guide here
In [36]: df.pivot(index = 'Client', columns = 'Ticker', values = 'PositionValue')
Out[36]:
Ticker A B C
Client
Client 1 1000 2000 10000
Client 2 300 6000 10000
Client 3 45345 546456 456456

Jim
- 398
- 1
- 6