如何在Python中找到那些具有单个值的列的列号?

如何在Python中找到那些具有单个值的列的列号?,python,python-3.x,Python,Python 3.x,我想找到单值列的列数:这是我的数据框: Cow_ID,Collar_label,BCS,Age_weeks,Height_cm,Weight_kg cow1,aq5t,90,14,90,120 cow2,aq4r,92,14,92,118 cow3,aq2f,87,14,87,120 cow4,aq7u,81,14,81,118 cow5,aq9p,93,14,93,120 cow6,aq4m,89,14,89,120 cow7,aq1v,86,14,86,118 cow8,aq2c,92,14

我想找到单值列的列数:这是我的数据框:

Cow_ID,Collar_label,BCS,Age_weeks,Height_cm,Weight_kg
cow1,aq5t,90,14,90,120
cow2,aq4r,92,14,92,118
cow3,aq2f,87,14,87,120
cow4,aq7u,81,14,81,118
cow5,aq9p,93,14,93,120
cow6,aq4m,89,14,89,120
cow7,aq1v,86,14,86,118
cow8,aq2c,92,14,92,120
cow9,aq5t,89,14,89,120
cow10,aq5x,88,14,88,118
这是我的代码,通过它我可以得到具有单个值的列名:

df = read_csv(filename, header=0)
print("Data frame size: ", df.shape)
print("Data frame : ", df)

# get the number of unique values for each column
counts = df.nunique()


print("number of unique values within each column:")
print(counts)
 

print("column with single value: ", counts[counts ==1])
但是我需要自动弹出列号而不是列名。
有什么建议吗?

获取单值系列的索引:

counts[counts ==1].index[0]
>> 'Age_weeks'
条件给出了与列号匹配的
True/False
列表:

df.columns == 'Age_weeks'
>> array([False, False, False,  True, False, False])
并使用
np.where
获取
True
项的索引,该索引等于您的列号:

np.where(df.columns == counts[counts ==1].index[0])
>>(array([3]),)
要获取号码:

np.where(df.columns == counts[counts ==1].index[0])[0][0]
>> 3

如果需要列的索引,请创建一个具有键、值对的字典,键为索引,值为列名

enum = dict(enumerate(df.columns))

column_nums = {v : k for k,v in enum.items() if v in counts[counts ==1].index}

{'Age_weeks': 3}


谢谢,你能解释一下这段代码是如何工作的吗:np.where(df.columns==counts[counts==1]。index[0])[0][0]。我是初学者,正在学习过程中,因此
counts[counts==1]
来自问题代码,返回一行pandas.Series,因为在“counts”系列中只有一项值为1。(顺便说一句,如果要处理多个项目,需要在此处进行迭代。)
.index[0]
返回此行的名称
df.columns
包含df的所有列名,因此
=
提供了一个与列匹配的布尔列表。最后,
np.where
返回
True
的索引,实际上是列号。谢谢,[0][0]的作用是什么?这是因为
np.where
返回的输出类型。它返回两个numpy数组的元组,每个数组包含一个维度的索引。在我们的例子中,布尔数组是一维的。所以我们得到一个“numpy数组”和“empty”的元组:
(数组([3]),)
。第一个
[0]
拾取元组的第一项,第二个
[0]
拾取numpy数组中的数字。@Manakin这没有给出列编号,它只显示列内容。你能纠正一下吗?我想试试你的代码
print(enum)

{0: 'Cow_ID',
 1: 'Collar_label',
 2: 'BCS',
 3: 'Age_weeks',
 4: 'Height_cm',
 5: 'Weight_kg'}