大熊猫中的[]和[[]]有什么区别?

elo*_*ong 4 python pandas

我对熊猫索引列的结果感到困惑。

db['varname']
Run Code Online (Sandbox Code Playgroud)

db[['varname']]
Run Code Online (Sandbox Code Playgroud)

给我'varname'的列值。但是,看起来有些细微的差别,因为的输出db['varname']显示了值的类型。

EdC*_*ica 7

首先寻找一个特定的 Key在df中的特定列,第二个是要从df中进行子选择的列的列表,因此它将返回与列表中的值匹配的所有列。

另一个微妙的事情是,即使您传递包含单个项目的列表,第一个默认情况下也会返回一个Series对象,而第二个默认情况下会返回一个对象DataFrame

例:

In [2]:
df = pd.DataFrame(columns=['VarName','Another','me too'])
df

Out[2]:
Empty DataFrame
Columns: [VarName, Another, me too]
Index: []

In [3]:    
print(type(df['VarName']))
print(type(df[['VarName']]))

<class 'pandas.core.series.Series'>
<class 'pandas.core.frame.DataFrame'>
Run Code Online (Sandbox Code Playgroud)

因此,当您传递列表时,它将尝试匹配所有元素:

In [4]:
df[['VarName','Another']]

Out[4]:
Empty DataFrame
Columns: [VarName, Another]
Index: []
Run Code Online (Sandbox Code Playgroud)

但是如果没有额外的东西,[]这将引发KeyError

df['VarName','Another']

KeyError: ('VarName', 'Another')
Run Code Online (Sandbox Code Playgroud)

因为您正试图查找名为:的列'VarName','Another',所以该列不存在