Cha*_* Ye 1 python numpy dataframe pandas
从一个非唯一的 Pandas 系列开始,可以通过 计算每个唯一值的数量.value_counts()。
>> col = pd.Series([1.0, 1.0, 2.0, 3.0, 3.0, 3.0])
0 1.0
1 1.0
2 2.0
3 3.0
4 3.0
5 3.0
dtype: object
>> stat = col.value_counts()
>> stat
3.0 3
1.0 2
2.0 1
dtype: int64
Run Code Online (Sandbox Code Playgroud)
但是,如果从两列的数据框开始,一列是唯一值,另一列是出现次数。(stat在前面的例子中)。如何将它们扩展为单个列。
因为我想计算这样一个数据框中数据的中位数、平均值等,我认为描述单列比两列容易得多。或者是否有任何方法可以在不扩展数据的情况下直接描述“value_count”数据帧?
# turn `stat` into col ???
>> col.describe()
count 6.000000
mean 2.166667
std 0.983192
min 1.000000
25% 1.250000
50% 2.500000
75% 3.000000
max 3.000000
Run Code Online (Sandbox Code Playgroud)
添加测试数据
>> df = pd.DataFrame({"Name": ["A", "B", "C"], "Value": [1,2,3], "Count": [2, 10, 2]})
>> df
Name Value Count
0 A 1 2
1 B 2 5
2 C 3 2
df2 = _reverse_count(df)
>> df2
Name Value
0 A 1
1 A 1
2 B 2
3 B 2
4 B 2
5 B 2
6 B 2
7 B 2
8 C 3
9 C 3
Run Code Online (Sandbox Code Playgroud)
您可以使用该repeat功能numpy
import pandas as pd
import numpy as np
col = pd.Series([1.0, 1.0, 2.0, 3.0, 3.0, 3.0])
stats=col.value_counts()
pd.Series(np.repeat(stats.index,stats))
# 0 3.0
# 1 3.0
# 2 3.0
# 3 1.0
# 4 1.0
# 5 2.0
# dtype: float64
Run Code Online (Sandbox Code Playgroud)
对于可以使用的多列
df.loc[df.index.repeat(df['Count'])]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
795 次 |
| 最近记录: |