How to use dataframe in Echart

hi, streamlit team and community.

I saw beautiful chart made of echart.
I tried to find a way in the community.
But I face error when I was tried plot my dataframe using echart.

  • error: ‘Could not convert component args to JSON’, TypeError(‘Object of type ndarray is not JSON serializable’

Tried to solve it in a known way but still couldn’t solve it

  • I tried : “data” : df[‘column’].values

If anyone knows how to draw an echart with my dataframe, please let me know.
thanks!

raw_data = {
    "Last Name": ["Miller", "Jacobson", "Ali", "Milner", "Smith"],
    "Age": [42, 52, 36, 24, 73],
}
df = pd.DataFrame(raw_data)

options = {
    "series": [
        {
            "type": "pie",
            "radius": "50%",
            # "data": df['Age'].values
            #-> error ('Could not convert component args to JSON', TypeError('Object of type ndarray is not JSON serializable'))
            "data": df['Age'].to_list()
             }
    ]
}
st_echarts(options=options)

Based from the example code on simple pie.

So we need to convert it.

# Data is a list of dict {'value': your_value, 'name': your_name}
edata = []
for value, name in zip(df['Age'].to_list(), df['Last Name'].to_list()):
    edata.append({'value': value, 'name': name})
options = {
    "tooltip": {"trigger": "item"},
    "series": [
        {
            "type": "pie",
            "radius": "50%",
            "data": edata
        }
    ]
}

And we got this.

image

Another way to get the required data format from df is by the use of the dataframe’s to_dict method. But we need to rename column names.

newdf = df.copy()  # in case we need the original df
newdf = newdf.rename(columns={'Age': 'value', 'Last Name': 'name'})
edata = newdf.to_dict('records')
2 Likes

thanks a lot ferdy!

I try study with your comment.