蟒蛇大熊猫 - 通过两个轴
问题描述:
选择数据框的一部分
比方说,我有这样的数据帧(DF):蟒蛇大熊猫 - 通过两个轴
A B C D
2013-01-05 0.785969 1.381685 -0.547796 -1.155653
2013-01-03 1.322663 0.343046 0.634790 -1.037137
2013-01-02 -0.132650 -0.030817 0.613637 -1.088943
2013-01-01 1.261990 -0.078801 0.425255 0.105730
2013-01-06 0.012660 -0.259059 -0.729147 0.122075
2013-01-04 -0.638154 -0.952552 0.895817 -0.749750
我知道如何让列A和B的横截面和所有行:
df.loc[:,["A", "B"]]
但是,如何获得某些列的横截面和某些行?
我试过的东西一样
df.loc[[2:], ["A", "B"]]
但只是返回一个错误。
答
因为ix is deprecated,你有2个可能的解决方案,如果需要通过标签与选择位置(.iloc)选择(的.loc):
转换位置索引名由seelcting指数[]
- 因此选择索引和值由标签,然后使用DataFrame.loc
:
print (df.index[2])
2013-01-02 00:00:00
df = df.loc[df.index[2]:, ["A", "B"]]
print (df)
A B
2013-01-02 -0.132650 -0.030817
2013-01-01 1.261990 -0.078801
2013-01-06 0.012660 -0.259059
2013-01-04 -0.638154 -0.952552
2.
CONVER列名由iloc
和位置由get_indexer
然后通过DataFrame.iloc
seelct:
print (df.columns.get_indexer(["A", "B"]))
[0 1]
df = df.iloc[2:, df.columns.get_indexer(["A", "B"])]
print (df)
A B
2013-01-02 -0.132650 -0.030817
2013-01-01 1.261990 -0.078801
2013-01-06 0.012660 -0.259059
2013-01-04 -0.638154 -0.952552
+0
对不起,我以前的评论,是我不好。它工作完美,谢谢! –
+0
超级,高兴能帮助! – jezrael
答
你可以尝试使用ILOC()方法
多列和行可以使用.iloc索引选择在一起。
多行和列的选择,使用和ILOC数据框
data.iloc[0:5] # first five rows of dataframe
data.iloc[:, 0:2] # first two columns of data frame with all rows
data.iloc[[2:], ["A","B"]] # 1st, 4th, 7th, 25th row + 1st 6th 7th columns.
data.iloc[0:5, 5:8] # first 5 rows and 5th, 6th, 7th columns of data frame (county -> phone1).
非常好,谢谢! –