如何使用python获取row_count?

时间:2018-08-21 05:03:31

标签: python pandas

我具有以下数据结构

ID Number   Product_Description
45452       MSSQL
45453       INFORMATICA
45454       INFORMATICA
45458       INFORMATICA
45456       MSSQL
45457       DBA

,输出应该是

MSSQL        2
INFORMATICA  3
DBA          1

我想将其存储在列表中

v_1 = [MSSQL,INFORMATICA,DBA]
v_2 = [2,3,1]

2 个答案:

答案 0 :(得分:2)

如果顺序很重要,请将GroupBy.sizesort=False一起使用:

s = df.groupby('Product_Description', sort=False).size()
print (s)
Product_Description
MSSQL          2
INFORMATICA    3
DBA            1
dtype: int64

v_1 = s.index.tolist()
v_2 = s.values.tolist()

print (v_1)
['MSSQL', 'INFORMATICA', 'DBA']
print (v_2)
[2, 3, 1]

如果顺序应该不同,例如Series.value_counts按发生次数排序:

s = df['Product_Description'].value_counts()
print (s)
INFORMATICA    3
MSSQL          2
DBA            1
Name: Product_Description, dtype: int64

v_1 = s.index.tolist()
v_2 = s.values.tolist()

print (v_1)
['INFORMATICA', 'MSSQL', 'DBA']

print (v_2)
[3, 2, 1]

另一种解决方案是创建列表字典:

df1 = df.groupby('Product_Description', sort=False).size().reset_index()
df1.columns=['v_1','v_2']
print (df1)
           v_1  v_2
0        MSSQL    2
1  INFORMATICA    3
2          DBA    1

d = df1.to_dict(orient='list')
print (d)
{'v_1': ['MSSQL', 'INFORMATICA', 'DBA'], 'v_2': [2, 3, 1]}

print (d['v_1'])
['MSSQL', 'INFORMATICA', 'DBA']

print (d['v_2'])
[2, 3, 1]

答案 1 :(得分:2)

您可以使用value_counts

p=df['Product_Description'].value_counts()
V_1=p.index.tolist()
V_2=p.values.tolist()