访问pandas值的第一列

2024-04-26 23:46:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用Python的pandas包中的value_counts()函数来查找列中项目的频率。它工作并输出以下内容:

57     1811
62      630
71      613
53      217
59      185
68       88
52       70

Name: hospitalized, dtype: int64

其中第一列是项,右列是其在列中的频率。

从那里开始,我想访问项的第一列,并在for循环中遍历它。我希望能够访问每行的项并检查它是否等于另一个值。如果这是真的,我希望能够访问第二列,并除以另一个数字。

我的大问题是从.value_counts()输出访问第一列。是否可以访问此列?如果可以,如何访问?这些列没有任何特定的名称(因为它只是值_counts()输出),所以我不确定如何访问它们。


Tags: 项目函数name名称pandasforvalue数字
2条回答

使用Panda的^{}

df = pd.DataFrame({'mycolumn': [1,2,2,2,3,3,4]})
for val, cnt in df.mycolumn.value_counts().iteritems():
    print 'value', val, 'was found', cnt, 'times'

value 2 was found 3 times
value 3 was found 2 times
value 4 was found 1 times
value 1 was found 1 times

value_counts返回熊猫系列:

df = pd.DataFrame(np.random.choice(list("abc"), size=10), columns = ["X"])
df["X"].value_counts()
Out[243]: 
c    4
b    3
a    3
Name: X, dtype: int64

对于单个值的数组,可以使用序列的索引:

vl_list = df["X"].value_counts().index
Index(['c', 'b', 'a'], dtype='object')

它是“Index”类型,但您可以对其进行迭代:

for idx in vl_list:
    print(idx)

c
b
a

或者对于numpy数组,可以使用df["X"].value_counts().index.values

相关问题 更多 >