Reputation: 21
I have the data looks like:
ws=[{'a': datetime.date(2020, 8, 31), 'b': <BB: 01>, 'c': <CC: 4>},
{'a': datetime.date(2020, 8, 31), 'b': <BB: 01>, 'c': <CC: 5>},
{'a': datetime.date(2020, 8, 31), 'b': <BB: 01>, 'c': <CC: 6>},
{'a': datetime.date(2020, 8, 31), 'b': <BB: 02>, 'c': <CC: 9>},
{'a': datetime.date(2020, 9, 1), 'b': <BB: 01>, 'c': <CC: 4>},
{'a': datetime.date(2020, 9, 1), 'b': <BB: 01>, 'c': <CC: 5>},
{'a': datetime.date(2020, 9, 1), 'b': <BB: 02>, 'c': <CC: 3>}]
And i wish to make it look like next, then render it to HTML.
\ a
b\ |2020-08-31| 2020-09-01|
---|----------|-----------|-----
01 |c= 4,5,6 |c= 4,5 |
02 |c= 9 |c= 3 |
Even though spending days of effort, i still do not have any idea. If someone can kindly give me some guidance, i will very very appreciate.
Upvotes: 2
Views: 231
Reputation: 12953
Working from your dictionary called ws
:
import pandas as pd
# convert the dic w to a dataframe:
pd.DataFrame.from_dict(ws)
# cast dataframe column types
pd.to_datetime(df['a'], format='%Y-%m0%d'))))
df['b'] = df['b'].astype(str)
df['c'] = df['c'].astype(str)
# pivot, (a) changing the default aggfunc to join the strings (b)
# set the column to be a, the index to be b:
df.pivot_table(columns='a', values='c', index='b', aggfunc={'c':lambda x: " ".join(x)}).fillna('')
Output:
a 2020-08-31 2020-09-01
b
<BB: 01> <CC: 4> <CC: 5> <CC: 6> <CC: 4> <CC: 5>
<BB: 02> <CC: 9> <CC: 3>
To render the dataframe in html, just use:
df.to_html()
Upvotes: 1