Mai*_*lam -2 python statistics pandas jupyter-notebook
开发总结此数据的频率分布。此数据是一个对象在 20 天内的需求。
2 1 0 2 1 3 0 2 4 0 3 2 3 4 2 2 2 4 3 0. 任务是在 jupyter notebook 中创建一个表,其中包含 Demand 和 Frequency 列。注意:需求必须按升序排列。这就是我所做的。
list_of_days = [2, 1, 0, 2, 1, 3, 0, 2, 4, 0, 3, 2 ,3, 4, 2, 2, 2, 4, 3, 0] # created a list of the data
import pandas as pd
series_of_days = pd.Series(list_of_days) # converted the list to series
series_of_days.value_counts(ascending = True) # the frequency was ascending but not the demand
test = dict(series_of_days.value_counts())
freq_table = pd.Series(test)
pd.DataFrame({"Demand":freq_table.index, "Frequency":freq_table.values})
Run Code Online (Sandbox Code Playgroud)
输出必须是这样的:
<table border = "1">
<tr>
<td>Demand</td>
<td>Frequency</td>
</tr>
<tr>
<td>0</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>7</td>
</tr>
<table>
Run Code Online (Sandbox Code Playgroud)
等等。有没有更好的方法来缩短 Python 代码?还是让它更有效率?
您可以使用value_countswithreset_index和排序方式sort_values:
df1 = pd.Series(list_of_days).value_counts()
.reset_index()
.sort_values('index')
.reset_index(drop=True)
df1.columns = ['Demand', 'Frequency']
print (df1)
Demand Frequency
0 0 4
1 1 2
2 2 7
3 3 4
4 4 3
Run Code Online (Sandbox Code Playgroud)
排序方式的另一个类似解决方案sort_index:
df1 = pd.Series(list_of_days)
.value_counts()
.sort_index()
.reset_index()
.reset_index(drop=True)
df1.columns = ['Demand', 'Frequency']
print (df1)
Demand Frequency
0 0 4
1 1 2
2 2 7
3 3 4
4 4 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17032 次 |
| 最近记录: |