熊猫按标签选择

时间:2020-04-25 05:49:22

标签: pandas dataframe

我无法理解loc运算符的以下操作。该屏幕快照取自熊猫官方documentation
原始数据帧位于第二个屏幕截图中。

Problem

Original Dataframe

1 个答案:

答案 0 :(得分:0)

开始分解代码实际上是一件好事,就像您在学校将数学问题分解为更简单的部分一样,以了解其行为:

import numpy as np
import pandas as pd

# Dataframe construction
df1 = pd.DataFrame(np.random.randn(6, 4),
                  index=list('abcdef'),
                  columns=list('ABCD'))

# Selection of the row indexed as 'a' using .loc():
df1.loc['a']

# Selection of the row indexed as 'a' using .loc() 
# where elements in this rows are strictly positive:
df1.loc['a'] > 0

# Selection of all entire columns where the elements
# in the row indexed as 'a' are strictly positive:
df1.loc[:, df1.loc['a'] > 0]

# Whole dataframe:
df1

警告,由于DataFrame是使用random numbers构建的,因此您几乎永远不会获得与文档中相同的结果。

相关问题