如何自动对熊猫数据框中的数据进行分类?
How to automatically categorise data in panda dataframe?
我有一个包含 1000 多行和 200 列的数据框,如下所示:
my_data:
ID, f1, f2, .. ,f200 Target
x1 3 0, .. ,2 0
x2 6 2, .. ,1 1
x3 5 4, .. ,0 0
x4 0 5, .. ,18 1
.. . ., .. ,.. .
xn 13 0, .. ,4 0
首先,我想将这些特征 (f1-f200) 自动离散为四组,即 no
、low
、medium
和 high
,以便在其列中具有零的ID(例如,x1在f2中包含0,在xn中相同..)应该是标签"no",其余应该分为低,中和高。
我发现了这个:
pd.cut(my_data,3, labels=["low", "medium", "high"])
但是,这并不能解决问题。有什么想法吗?
使用np.select
# Iterate over the Dataframe Columns i.e. f1-f200
for col in df.columns:
# Define your Condition
conditions = [
(df[col] == 0),
(df[col] == 1),
(df[col] == 2),
(df[col] > 3)]
# Values you want to map
choices = ['no','Low', 'Medium', 'High']
df[col] = np.select(conditions, choices, default='Any-value')
因此,您需要创建动态 bin 并迭代列来获得它。这可以通过以下方式完成:
new_df = pd.DataFrame()
for name,value in df1.iteritems(): ##df1 is your dataframe
bins = [-np.inf, 0,df1[name].min()+1,df1[name].mean(), df1[name].max()]
new_df[name] = pd.cut(df1[name], bins=bins, include_lowest=False, labels=['no','low', 'mid', 'high'])
我有一个包含 1000 多行和 200 列的数据框,如下所示:
my_data:
ID, f1, f2, .. ,f200 Target
x1 3 0, .. ,2 0
x2 6 2, .. ,1 1
x3 5 4, .. ,0 0
x4 0 5, .. ,18 1
.. . ., .. ,.. .
xn 13 0, .. ,4 0
首先,我想将这些特征 (f1-f200) 自动离散为四组,即 no
、low
、medium
和 high
,以便在其列中具有零的ID(例如,x1在f2中包含0,在xn中相同..)应该是标签"no",其余应该分为低,中和高。
我发现了这个:
pd.cut(my_data,3, labels=["low", "medium", "high"])
但是,这并不能解决问题。有什么想法吗?
使用np.select
# Iterate over the Dataframe Columns i.e. f1-f200
for col in df.columns:
# Define your Condition
conditions = [
(df[col] == 0),
(df[col] == 1),
(df[col] == 2),
(df[col] > 3)]
# Values you want to map
choices = ['no','Low', 'Medium', 'High']
df[col] = np.select(conditions, choices, default='Any-value')
因此,您需要创建动态 bin 并迭代列来获得它。这可以通过以下方式完成:
new_df = pd.DataFrame()
for name,value in df1.iteritems(): ##df1 is your dataframe
bins = [-np.inf, 0,df1[name].min()+1,df1[name].mean(), df1[name].max()]
new_df[name] = pd.cut(df1[name], bins=bins, include_lowest=False, labels=['no','low', 'mid', 'high'])