<jupyter_start><jupyter_text>How to export your beautiful grid in a dataframe? Now you have pivoted columns, aggregated, edited your data, it is time to export the data back to python. Remember the time when fitting your data from excel to python was a pain, inefficient and time-consuming ? Then you should definitely use the export features.<jupyter_code>import os
import json
import pandas as pd
import numpy as np
import urllib.request as ur
from ipyaggrid import Grid<jupyter_output><empty_output><jupyter_text>Export simple data Done only some filtering and sorting ? Export simple data from your grid. In auto-export mode, you can get the data you wand directly in dataframes as you click the grid.<jupyter_code>def mklbl(prefix, n):
    return ["%s%s" % (prefix, i) for i in range(n)]

miindex = pd.MultiIndex.from_product([mklbl('A', 4),
                                      mklbl('B', 2),
                                      mklbl('C', 4),
                                      mklbl('D', 2)],
                                    names=['RowIdx-1', 'RowIdx-2', 'RowIdx-3', 'RowIdx-4'])
index  =['-'.join(col).strip() for col in miindex.values]
micolumns = pd.MultiIndex.from_tuples([('a', 'foo', 'zap'),
                                       ('a', 'foo', 'zip'),
                                       ('a', 'bar', 'zap'),
                                       ('a', 'bar', 'zip'),
                                       ('b', 'foo', 'zap'),
                                       ('b', 'foo', 'zep'),
                                       ('b', 'bah', 'zep'),
                                       ('b', 'bah', 'zyp'),
                                       ('b', 'bah', 'zap'),
                                      ],
                                      names=['ColIdx-{}'.format(i) for i in range(1, 4)])
cols  =['-'.join(col).strip() for col in micolumns.values]
data = np.arange(len(miindex) * len(micolumns), dtype=np.float).reshape((len(miindex),len(micolumns)))
data = data.tolist()
df  = pd.DataFrame(data, index=index, columns=cols).sort_index()
df  = pd.DataFrame(data, index=index, columns=cols).sort_index()
df.index.name = 'UniqueRow'
df.columns.name = 'UniqueCol'

column_defs_1 = [{'field': df.index.name}] + [{'field': c} for c in df.columns[:5]]


grid_options_1 = {
    'columnDefs' : column_defs_1,
    'enableSorting': 'true',
    'enableFilter': 'true',
    'enableColResize': 'false',
    'enableRangeSelection': 'true',
    'rowSelection': 'multiple',
}

grid1 = Grid(grid_data=df,
            grid_options=grid_options_1,
            quick_filter=True,
            export_csv=False,
            export_excel=False,
            #show_toggle_edit=True,
            export_mode='auto',
            index=True,
            keep_multiindex=False,
            theme='ag-theme-fresh')
grid1<jupyter_output><empty_output><jupyter_text>Now try to sort, filter and select specific parts of the grid with the range selection and observe the value of grid_data_out.<jupyter_code>grid1.grid_data_out.get('grid')
grid1.grid_data_out.get('rows')
#grid1.grid_data_out.get('cols')
#grid1.grid_data_out.get('range')<jupyter_output><empty_output><jupyter_text>With other options like row selection, we get another way of exporting the data. Please try to remove columns, selecting several lines and observe the export values.<jupyter_code>column_defs_2 = [{'field': df.index.name}] + [{'field': c} for c in df.columns[:5]]

grid_options_2 = {
    'columnDefs' : column_defs_2,
    'enableSorting': 'true',
    'enableFilter': 'true',
    'enableColResize': 'false',
    'rowSelection': 'multiple',
}

grid2 = Grid(grid_data=df,
            grid_options=grid_options_2,
            quick_filter=True,
            export_csv=False,
            export_excel=False,
            show_toggle_edit=True,
            export_mode='buttons',
            index=True,
            keep_multiindex=False,
            theme='ag-theme-fresh')
grid2
grid2.grid_data_out.get('grid')
grid2.grid_data_out.get('rows')<jupyter_output><empty_output><jupyter_text>Exporting more complex grids Now let's try to export more complex grids. With huge/complex data, we often want to export the data "as is". The export grid feature is available with the `button-export` mode.<jupyter_code>url = 'https://raw.githubusercontent.com/ag-grid/ag-grid-docs/master/src/olympicWinners.json'
with ur.urlopen(url) as res:
    data = json.loads(res.read().decode('utf-8'))
    
columnDefs = [
    {'headerName': "Country", 'field': "country", 'width': 120, 'rowGroup': 'true'},
    {'headerName': "Year", 'field': "year", 'width': 90, 'pivot': 'true'},
    {'headerName': "Sport", 'field': "sport", 'width': 110, 'rowGroup': 'true'},
    {'headerName': "Athlete", 'field': "athlete"},
    {'headerName': "Gold", 'field': "gold", 'width': 100, 'aggFunc': 'sum'},
    {'headerName': "Silver", 'field': "silver", 'width': 100, 'aggFunc': 'sum'},
    {'headerName': "Bronze", 'field': "bronze", 'width': 100, 'aggFunc': 'sum'},
];

gridOptions = {
    'pivotMode': 'true',
    'enableColResize': 'true',
    'columnDefs': columnDefs,
    'enableFilter':'true',
    'enableSorting':'true',
    'animateRows':'true',
};

pivot = Grid(export_mode='auto',
             export_csv=True,
             export_excel=True,
             quick_filter=True,
             theme='ag-theme-fresh',
             compress_data=True,
             grid_options=gridOptions,
             grid_data=data,
             columns_fit='auto',
             hide_grid=False)
pivot<jupyter_output><empty_output><jupyter_text>You could of course export the grid to CSV or Excel if you're a bit old fashioned, but an option to consider is definitely to export it directly to python via `grid_data_out`.You see that the data in the first column has been grouped several times. You can thus choose to display the aggregated data at the country level or at the sport level by incrementing the counter next to the *Export Grid* button. Then try to export the grid by clicking the button `Export Grid` and observe the result.<jupyter_code>pivot.grid_data_out['grid']<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13676326929338978, 'fraction_numerical': 0.007815043959622273, 'mean_word_length': 2.764093137254902, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '551234', 'license': 'MIT', 'n_tokens_mistral': 1930, 'n_tokens_neox': 1860, 'n_words': 511, 'path': 'docs/notebooks/demo-ipyaggrid-export-data.ipynb', 'repo_name': 'DGothrek/ipyaggrid', 'size': '6142'}