このノートブックは、pandasのドキュメントの10 Minutes to pandasを写経したものです。
In [1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
In [2]:
s = pd.Series([1,3,5,np.nan,6,8])
s
Out[2]:
In [3]:
dates = pd.date_range('20130101', periods=6)
dates
Out[3]:
In [4]:
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
df
Out[4]:
In [5]:
df2 = pd.DataFrame({ 'A': 1.,
'B': pd.Timestamp('20130102'),
'C': pd.Series(1, index=list(range(4)), dtype='float32'),
'D': np.array([3] * 4, dtype='int32'),
'E': pd.Categorical(['test', 'train', 'test', 'train']),
'F': 'foo' })
df2
Out[5]:
In [6]:
df2.dtypes
Out[6]:
In [7]:
df.head()
Out[7]:
In [8]:
df.tail(3)
Out[8]:
In [9]:
df.index
Out[9]:
In [10]:
df.columns
Out[10]:
In [11]:
df.values
Out[11]:
In [12]:
df.describe()
Out[12]:
In [13]:
df.T
Out[13]:
In [14]:
df.sort_values(by='B')
Out[14]:
In [15]:
df['A']
Out[15]:
In [16]:
df[0:3]
Out[16]:
In [17]:
df.loc[dates[0]]
Out[17]:
In [18]:
df.loc[:, ['A', 'B']]
Out[18]:
In [19]:
df.loc['20130102': '20130104', ['A', 'B']]
Out[19]:
In [20]:
df.loc['20130102', ['A', 'B']]
Out[20]:
In [21]:
df.loc[dates[0], 'A']
Out[21]:
In [22]:
df.at[dates[0], 'A']
Out[22]:
In [23]:
df.iloc[3]
Out[23]:
In [24]:
df.iloc[3:5, 0:2]
Out[24]:
In [25]:
df.iloc[[1, 2, 4], [0, 2]]
Out[25]:
In [26]:
df.iloc[1:3, :]
Out[26]:
In [27]:
df.iloc[:, 1:3]
Out[27]:
In [28]:
df.iloc[1, 1]
Out[28]:
In [29]:
df.iat[1, 1]
Out[29]:
In [30]:
df[df.A > 0]
Out[30]:
In [31]:
df[df > 0]
Out[31]:
In [32]:
df2 = df.copy()
df2['E'] = ['one', 'one', 'two', 'three', 'four', 'three']
df2
Out[32]:
In [33]:
df2[df2['E'].isin(['two', 'four'])]
Out[33]:
In [34]:
df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ['E'])
df1.loc[dates[0]: dates[1], 'E'] = 1
df1
Out[34]:
In [44]:
df1.dropna(how='any')
Out[44]:
In [45]:
df1.fillna(value=5)
Out[45]:
In [46]:
pd.isnull(df1)
Out[46]:
In [47]:
df.mean()
Out[47]:
In [48]:
df.mean(1)
Out[48]:
In [49]:
s = pd.Series([1,3,5,np.nan,6,8], index=dates).shift(2)
s
Out[49]:
In [50]:
df.sub(s, axis='index')
Out[50]:
In [51]:
df.apply(np.cumsum)
Out[51]:
In [52]:
df.apply(lambda x: x.max() - x.min())
Out[52]:
In [53]:
s = pd.Series(np.random.randint(0, 7, size=10))
s
Out[53]:
In [54]:
s.value_counts()
Out[54]:
In [55]:
s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
s.str.lower()
Out[55]:
In [56]:
df = pd.DataFrame(np.random.randn(10, 4))
df
Out[56]:
In [58]:
pieces = [df[:3], df[3:7], df[7:]]
pd.concat(pieces)
Out[58]:
In [59]:
left = pd.DataFrame({'key': ['foo', 'foo'], 'lval': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'foo'], 'rval': [4, 5]})
left
Out[59]:
In [60]:
right
Out[60]:
In [61]:
pd.merge(left, right, on='key')
Out[61]:
In [62]:
left = pd.DataFrame({'key': ['foo', 'bar'], 'lval': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'bar'], 'rval': [4, 5]})
left
Out[62]:
In [63]:
right
Out[63]:
In [64]:
pd.merge(left, right, on='key')
Out[64]:
In [65]:
df = pd.DataFrame(np.random.randn(8, 4), columns=['A', 'B', 'C', 'D'])
df
Out[65]:
In [66]:
s = df.iloc[3]
df.append(s, ignore_index=True)
Out[66]:
In [67]:
df = pd.DataFrame({ 'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.random.randn(8) })
df
Out[67]:
In [68]:
df.groupby('A').sum()
Out[68]:
In [69]:
df.groupby(['A', 'B']).sum()
Out[69]:
In [70]:
tuples = list(zip(*[['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(8, 2), index=index, columns=['A', 'B'])
df2 = df[:4]
df2
Out[70]:
In [71]:
stacked = df2.stack()
stacked
Out[71]:
In [72]:
stacked.unstack()
Out[72]:
In [73]:
stacked.unstack(1)
Out[73]:
In [74]:
stacked.unstack(0)
Out[74]:
In [76]:
df = pd.DataFrame({ 'A': ['one', 'one', 'two', 'three'] * 3,
'B': ['A', 'B', 'C'] * 4,
'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2,
'D' : np.random.randn(12),
'E' : np.random.randn(12) })
In [77]:
pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'])
Out[77]:
In [ ]:
rng = pd.date_range('1/1/2012', periods=100, freq='S')
In [35]:
df = pd.DataFrame({"id": [1, 2, 3, 4, 5, 6], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']})
In [36]:
df["grade"] = df["raw_grade"].astype("category")
df["grade"]
Out[36]:
In [37]:
df["grade"].cat.categories = ["very good", "good", "very bad"]
In [38]:
df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium",
"good", "very good"])
df["grade"]
Out[38]:
In [39]:
df.sort_values(by="grade")
Out[39]:
In [40]:
df.groupby("grade").size()
Out[40]:
In [41]:
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
ts.plot()
Out[41]:
In [42]:
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=['A', 'B', 'C', 'D'])
df = df.cumsum()
plt.figure(); df.plot(); plt.legend(loc='best')
Out[42]:
In [43]:
if pd.Series([False, True, False]):
print("I was true")