- pandas的创建
与series相似,也是存放data与index。与series不同的是,panda中的data存放的是键值对。如下
data = {'Bob' : pd.Series([245, 25, 55]),
'Alice' : pd.Series([40, 110, 500, 45])
df = pd.DataFrame(data) # index可放可不放,若不放index则会
会自动在index位置填充序号,如果想要填充index的话,可以如series一样添加。例如
data = {'Bob' : pd.Series([245, 25, 55]),
'Alice' : pd.Series([40, 110, 500, 45])
df = pd.DataFrame(data) # index可放可不放,若不放index则会自动生成标号
- pandas索引
一个原则 先索引列,再索引行。
store_items['bikes']['store 1']
>>> 20
使用某一列里的值与另一个列名来索引
list(store_items[store_items['bikes']==20]['pants'])
>>> 30
- 添加列
-
list(store_items[store_items['bikes']==20]['pants'])
- 使用append添加行
# We create a dictionary from a list of Python dictionaries that will number of items at the new store
new_items = [{'bikes': 20, 'pants': 30, 'watches': 35, 'glasses': 4,'sexy lady':'37E'}]
# We create new DataFrame with the new_items and provide and index labeled store 3
new_store = pd.DataFrame(new_items, index = ['store 3'])
# We display the items at the new store
new_store
- 删除
pop:仅可以删除列
store_items.pop('bikes'),并且返回删除的列
drop:不仅可以删除列,还可以删除行。用法下面详解
首先补充一个基本知识,在pandas中axis常常用到。若axis=0,则是在行的维度上操作,如下
store_items = a.drop(['store 2', 'store 1'], axis = 0)
# we display the modified DataFrame
store_items
若axis=1,则是在列的维度上进行操作
store_items = a.drop(['glasses'], axis = 1)
# we display the modified DataFrame
store_items