pandas中dataframe的索引问题

一:通过行标签索引

1.通过行标签索引行数据  index可以为整数

import pandas as pd
data = [[1,2,3],[4,5,6]]
index = [0,1]
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.loc[1]

2.  行标签索引  index为字符

import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.loc['d']

3.  索引列数据时 如下操作会出错:

import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.loc['a']
'''
KeyError: 'the label [a] is not in the [index]'
'''

 4.多行获取

import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.loc['d':]
'''
a b c
d 1 2 3
e 4 5 6
'''

5.索引某行某列

import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.loc['d',['b','c']]
'''
b 2
c 3
'''

6.索引某列

import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.loc[:,['c']]
'''
c
d 3
e 6
'''

二:iloc通过行号索引

import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.loc[1]
'''
a 4
b 5
c 6
'''

2.通过行号多行索引

import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.iloc[0:]
'''
a b c
d 1 2 3
e 4 5 6
'''

3.iloc索引列

import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.iloc[:,[1]]
'''
b
d 2
e 5
'''

 

三.ix  两种方式loc 和iloc结合的方式

1.通过行号索引

import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.ix[1]
'''
a 4
b 5
c 6
'''

2.通过行标签索引

import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.ix['e']
'''
a 4
b 5
c 6
'''

转载于:https://www.cnblogs.com/GY-Zhu/p/9626237.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值