读,写,存储操作
Import
import pandas as pd
Creating data
1. DataFrame
是一个table, 其中包含由独立entries组成的array,每一个entry对应于一行和一列
表达形式
(1)
pd.DataFrame({‘列名’:[列中的value1,value2。。。],
‘列名2’:[列中的value1,value2。。。]},
index=[‘行标签1’,‘2’])
pd.DataFrame({'Blue': ['I liked it.', 'It was awful.'],
'Yellow': ['Pretty good.', 'Bland.']},
index=['Mom', 'Dad'])

(2)或者可以使用
pd.DataFrame([[30, 21],[22,21]] (每一行的数据),
columns=[‘Apples’, ‘Bananas’](列标签),
index = [‘a’,‘b’](行标签))
fruits = pd.DataFrame([[30, 21],[22,21]],
columns=['Apples', 'Bananas'],
index = ['a','b'])

2. Series
是一个list,是一个有序序列
实际上Series是DataFrame的一个列
pd.Series([30, 35, 40],
index=['2015 Sales', '2016 Sales', '2017 Sales'],
name='Product A')
Out:
2015 Sales 30
2016 Sales 35
2017 Sales 40
Name: Product A, dtype: int64
或者也可以分开写:
quantities = ['4 cups', '1 cup', '2 large', '1 can']
items = ['Flour', 'Milk', 'Eggs', 'Spam']
recipe = pd.Series(quantities, index=items, name='Dinner')
Reading Data
reviews = pd.read_csv(
'../input/wine-reviews/winemag-data_first150k.csv',
index_col=0)
index_col = 你想要选择的index列
(=0: 设置第一列为index列)
查看大小
reviews.shape
Out:
(129971, 14)
输出前五行
reviews.head()
输出后五行
reviews.tail()
DataFrame 保存为csv文件
animals.to_csv('cows_and_goats.csv')
Select,访问(Accessor)
select一列
desc = reviews.description
或者
desc = reviews["description"]
这里读desc是Series object
如果列名中有空格, 例如 ‘object name’只能用第二种方法
Select一个value
reviews['country'][0]
Index
1. Index-based selection
select第一行
reviews.iloc[0]
select第1列
iloc【(行),(列)】
reviews.iloc[:, 0]
select第一列的前三行
reviews.iloc[:3, 0]
Out:
0 Italy
1 Portugal
2 US
Name: country, dtype: object
select第一列的二三行
【1,3) 包前不包后
reviews.iloc[1:3, 0]
也可以直接写所想选的行
reviews.iloc[[0, 1, 2], 0]
负号:倒数第几个
(扩展:在R语言中,-1指除了第2列都显示)
reviews.iloc[-5:]
2. Label-based selection
reviews.loc[:, ['taster_name', 'taster_twitter_handle', 'points']]
3. Set index
reviews.set_index("title")
4. 条件搜索select
reviews.country == 'Italy'
Out:
0 True
1 False
...
129969 False
129970 False
Name: country, Length: 129971, dtype: bool
可以放进loc中,只select出country是Italy的value
reviews.loc[reviews.country == 'Italy']
&(ampersand)
reviews.loc[(reviews.country == 'Italy') & (reviews.points >= 90)]
|(pipe)
reviews.loc[(reviews.country == 'Italy') | (reviews.points >= 90)]
.isin()
reviews.loc[reviews.country.isin(['Italy', 'France'])]
.isnull()/.notnull()
reviews.loc[reviews.price.notnull()]
iloc 和loc区别
iloc :第一个包括,最后一个不包括
loc:全部包括
例子:
df.iloc[0:6] 返回:0,1,2,3,4,5
df.loc[0:6] 返回:0,1,2,3,4,5,6
df = reviews.loc[0:99,['country','variety']]
#or
df = reviews.iloc[0:100,[0,11]]
版权声明:本文为weixin_40319336原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。