繁体   English   中英

Python:从列表创建2列数据框并在列表上进行计算

[英]Python: Creating a 2-column dataframe from list and a computation on the list

我正在使用python迈出第一步,希望您可以在以下方面为我提供帮助:

我有一个清单

scores = [1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5]

我想创建一个数据框,该数据框在第1列中具有得分,在第2列中具有得分的频率。

任何帮助或指针表示赞赏。 谢谢!

我的第一次尝试不是很好:

scores = [1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5]
freq = []
df = {'col1': scores, 'col2': freq}

首先,创建一个Counter对象来计算每个乐谱的频率。

In [1]: scores = [1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5]

In [2]: from collections import Counter

In [3]: score_counts = Counter(scores)

In [4]: score_counts
Out[4]: Counter({5: 12, 4: 8, 3: 4, 1: 3, 2: 3})

In [5]: import pandas as pd

In [6]: pd.DataFrame.from_dict(score_counts, orient='index')
Out[6]: 

    0
1   3
2   3
3   4
4   8
5  12

[5 rows x 1 columns]

可能会使某些用户绊倒的部分是pd.DataFrame.from_dict() 该文档位于此处: http : //pandas.pydata.org/pandas-docs/dev/genic/pandas.DataFrame.from_dict.html

我将使用value_counts (例如, 此处为Series文档)。 请注意,我在这里稍微更改了数据:

>>> import pandas as pd
>>> scores = [1]*3 + [2]*3 + [3]*4 + [4]*1 + [5]*4
>>> pd.value_counts(scores)
5    4
3    4
2    3
1    3
4    1
dtype: int64

您可以根据需要更改输出:

>>> pd.value_counts(scores, ascending=True)
4    1
1    3
2    3
3    4
5    4
dtype: int64
>>> pd.value_counts(scores).sort_index()
1    3
2    3
3    4
4    1
5    4
dtype: int64
>>> pd.value_counts(scores).sort_index().to_frame()
   0
1  3
2  3
3  4
4  1
5  4

要计算频率:

freq = {}
for score in scores:
     freq[score] = freq.get(score, 0) + 1

这将为您提供一个字典,其中的键映射到键值的频率。 然后,要创建两列,您可以只创建一个字典,例如:

data = {'scores': scores, 'freq': freq}

您也可以使用列表理解来实现此目的,其中列表的索引等于您的分数,值是频率,但是如果分数的范围较大,则将需要较大的稀疏数组,因此您可能会更好如上使用字典

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM