Select a multiple-key cross section from a DataFrame

There are better ways of doing this with more recent versions of Pandas (see Multi-indexing using slicers in the changelog for version 0.14): regression_df.loc[(slice(None), [‘SPY’, ‘GLD’]), :] This can be made more readable with the use of pd.IndexSlice: df.loc[pd.IndexSlice[:, [‘SPY’, ‘GLD’]], :] With the convention idx = pd.IndexSlice, this becomes df.loc[idx[:, [‘SPY’, ‘GLD’]], :]

Create a pandas DataFrame from multiple dicts [duplicate]

To make a DataFrame from a dictionary, you can pass a list of dictionaries: >>> person1 = {‘type’: 01, ‘name’: ‘Jhon’, ‘surname’: ‘Smith’, ‘phone’: ‘555-1234’} >>> person2 = {‘type’: 01, ‘name’: ‘Jannette’, ‘surname’: ‘Jhonson’, ‘credit’: 1000000.00} >>> animal1 = {‘type’: 03, ‘cname’: ‘cow’, ‘sciname’: ‘Bos….’, ‘legs’: 4, ‘tails’: 1 } >>> pd.DataFrame([person1]) name phone surname … Read more

Pandas to_sql to sqlite returns ‘Engine’ object has no attribute ‘cursor’

adding in a raw_connection() worked for me from sqlalchemy import create_engine sql_engine = create_engine(‘sqlite:///test.db’, echo=False) connection = sql_engine.raw_connection() working_df.to_sql(‘data’, connection, index=False, if_exists=”append”) I had conda install sqlalchemy during my notebook session, so while it was accessible, since I already initiated pandas, it appeared as if there was no sqlalchemy. Restarting the session allowed me to … Read more

Counting frequency of values by date using pandas

It might be easiest to turn your Series into a DataFrame and use Pandas’ groupby functionality (if you already have a DataFrame then skip straight to adding another column below). If your Series is called s, then turn it into a DataFrame like so: >>> df = pd.DataFrame({‘Timestamp’: s.index, ‘Category’: s.values}) >>> df Category Timestamp … Read more

Calculate Arbitrary Percentile on Pandas GroupBy

You want the quantile method: In [47]: df Out[47]: A B C 0 0.719391 0.091693 one 1 0.951499 0.837160 one 2 0.975212 0.224855 one 3 0.807620 0.031284 one 4 0.633190 0.342889 one 5 0.075102 0.899291 one 6 0.502843 0.773424 one 7 0.032285 0.242476 one 8 0.794938 0.607745 one 9 0.620387 0.574222 one 10 0.446639 0.549749 … Read more