1 回答

TA貢獻1831條經(jīng)驗 獲得超4個贊
計算數(shù)據(jù)幀中每個值的出現(xiàn)次數(shù),將頻率范圍以 10 為一組進行分組,然后為每個范圍創(chuàng)建
dict
一個DataFrames
。垃圾箱標(biāo)簽將成為
dict
鑰匙該
bins
列是分類的,因此.groupby
將為每個標(biāo)簽創(chuàng)建一個組,即使該組為空,因此使用pandas.DataFrame.empty
,因此只有非空組才會添加到dict
of 中DataFrames
。替換
g: dfg
為中g: pd.DataFrame(dfg.B)
只有列。?B
dict
使用
dfg.reset_index(drop=True)
或pd.DataFrame(dfg.B).reset_index(drop=True)
刪除原始索引。labels
使用,因為它們更容易用作dict
密鑰如果不使用
labels
,dict
鍵將是Interval
, 就像[Interval(10, 20, closed='right')
,這很麻煩。df.B.map(df.groupby('B')['B'].count())
也有效,但不是必需的。
使用
pandas.Series.value_counts()
和pandas.Series.map
在 中創(chuàng)建一個計數(shù)列df
,它將傳達列中值的頻率B
。用于
pd.cut
對頻率范圍進行分類pandas.DataFrame.groupby
與 a 一起使用可根據(jù) bin 標(biāo)簽?dict-comprehension
創(chuàng)建dict
of 。DataFrames
import pandas as pd
import numpy as np
# setup test dataframe
np.random.seed(365)
df = pd.DataFrame({'B': np.random.randint(5238, size=(200000))})
# add a counts column to the dataframe
df['counts'] = df.B.map(df.B.value_counts())
# create a bins column for the frequency range
bins = range(0, 201, 10)
labels = range(10, 201, 10)
df['bins'] = pd.cut(df.counts, bins=bins, right=True, labels=labels)
# display(df.head())
? ? ? B? counts bins
0? 2740? ? ? 37? ?40
1? 4897? ? ? 41? ?50
2? 4955? ? ? 45? ?50
3? ?428? ? ? 31? ?40
4? ?226? ? ? 34? ?40
# create a dict of dataframes for the non-empty bins
dfd = {g: dfg for g, dfg in df.groupby('bins') if not dfg.empty}
# print dict keys
dfd.keys()
[out]:
dict_keys([20, 30, 40, 50, 60, 70])
# display(dfd[20].head())
? ? ? ? ? B? counts bins
5350? ?4986? ? ? 19? ?20
5646? ?4952? ? ? 20? ?20
11232? 3728? ? ? 19? ?20
11707? 2819? ? ? 20? ?20
13547? 3728? ? ? 19? ?20
添加回答
舉報