我对pandas中索引列的结果感到困惑。
两者
db['varname']
和
db[['varname']]
请给我“varname”列的值。不过似乎有一些细微差别,因为db['varname']
的输出结果显示了值的类型。
第一个函数在您的df中查找特定的Key
,即特定的列,第二个函数是要从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'>
当你传递一个列表时,它会尝试匹配所有的元素:
In [4]:
df[['VarName','Another']]
Out[4]:
Empty DataFrame
Columns: [VarName, Another]
Index: []
如果没有额外的[]
,那么就会引发KeyError
:
df['VarName','Another']
KeyError: ('VarName', 'Another')
因为您正在尝试查找名为:'VarName','Another'
的列,但该列不存在
[[
运算符。df[['col_name']]
时,你实际上看到的是:col_names = ['col_name']
df[col_names]
[[
唯一的作用是将结果变成 DataFrame,而不是 Series。
在 DataFrame 上使用 [
时会查看参数的类型;如果是标量,则只返回一个列并将其作为 Series 返回;如果是列表,则返回包含这些列的 DataFrame。
就是这样!
In [84]: single_brackets = np.array( [ 0, 13, 31, 1313 ] )
In [85]: single_brackets.shape, single_brackets.ndim
Out[85]: ((4,), 1)
# (4, ) : is 4-Elements/Values
# 1 : is One_Dimensional array (Generally...In Pandas we call 1D-Array as "SERIES")
In [86]: double_brackets = np.array( [[ 0, 13, 31, 1313 ]] )
In [87]: double_brackets.shape, double_brackets.ndim
Out[87]: ((1, 4), 2)
#(1, 4) : is 1-row and 4-columns
# 2 : is Two_Dimensional array (Generally...In Pandas we call 2D-Array as "DataFrame")
这是NumPy的概念...不要怪Pandas
仍然不相信吗?看看这个:
In [89]: three_brackets = np.array( [[[ 0, 13, 31, 1313 ]]] )
In [93]: three_brackets.shape, three_brackets.ndim
Out[93]: ((1, 1, 4), 3)
# (1, 1, 4) -> In general....(rows, rows, columns)
# 3 -> Three_Dimensional array
工作在创建一些NumPy数组,使用“reshape”命令并检查“ndim”属性。
[]
将返回pandas.core.series.Series
,而[[]]
将返回pandas.core.frame.DataFrame
。两者在pandas中是不同的数据结构。db[['varname']]
,它具有2D形状。from sklearn.preprocessing import KBinsDiscretizer kbinsDiscretizer
est = KBinsDiscretizer(n_bins=3, encode='onehot-dense', strategy='uniform')
est.fit(db[['varname']]) # where use dfb['varname'] causes error