Python中项目的标记
我有一个数据框,如下所示:Python中项目的标记,python,pandas,Python,Pandas,我有一个数据框,如下所示: Id Type 0 14035 A 1 14035 B 2 14035 C 3 24259 A 4 24259 B 我正在尝试使用python进行一些分类,如果它包含
Id Type
0 14035 A
1 14035 B
2 14035 C
3 24259 A
4 24259 B
我正在尝试使用python进行一些分类,如果它包含ABC/BAC/CBA排列,则将其分类在类别1中。如果仅包含AB/BA,则将其归类为第2类
Id Classification
0 14035 Category 1
3 24259 Category 2
我曾想过使用一个groupby并将其放入arry,但我不确定是否要这样做,因为我对Python还是新手
有什么帮助吗
谢谢 这里您可以使用
groupby
:
df.groupby("Id")["Type"].apply(lambda x: "Category 1" if x.str.cat() == "ABC" else "Category 2")
输出:
Id
14035 Category 1
24259 Category 2
Name: Type, dtype: object
这里您可以使用
groupby
:
df.groupby("Id")["Type"].apply(lambda x: "Category 1" if x.str.cat() == "ABC" else "Category 2")
输出:
Id
14035 Category 1
24259 Category 2
Name: Type, dtype: object
以下是一个相当普遍的解决方案:
# Find which elements are present in each id
elements_in_id = df.groupby('Id').apply(lambda x: x.astype(str).sum())['Type']
categories = {"ABC" : 'Category 1', "AB" : 'Category 2'}
# Assign category if present, otherwise assign "Not Classified"
# Assume that the keys in categories contain letters sorted alphabetically
result = elements_in_id.map(lambda x: categories.get(''.join(sorted(x)), 'Not Classified'))
它给出了预期的输出:
Id
14035 Category 1
24259 Category 2
以下是一个相当普遍的解决方案:
# Find which elements are present in each id
elements_in_id = df.groupby('Id').apply(lambda x: x.astype(str).sum())['Type']
categories = {"ABC" : 'Category 1', "AB" : 'Category 2'}
# Assign category if present, otherwise assign "Not Classified"
# Assume that the keys in categories contain letters sorted alphabetically
result = elements_in_id.map(lambda x: categories.get(''.join(sorted(x)), 'Not Classified'))
它给出了预期的输出:
Id
14035 Category 1
24259 Category 2
尽管前面的解决方案很有效,但我关心的是所使用的字符串连接 在以下情况下,此类字符串连接将无法对ID进行分类:
,即:('ABCD'!='ABC')
import pandas as pd
import numpy as np
# Construct sample dataframe
df = pd.DataFrame()
df['Id'] = ['14035', '14035', '14035', '24259', '24259', ]
df['Type'] = ['A', 'B', 'C', 'A', 'B', ]
# Define classification logic
def classification_logic(list_of_types):
if set(['A', 'B', 'C']) <= set(list_of_types):
return 1
if set(['A', 'B']) <= set(list_of_types):
return 2
return np.nan
# Apply to groups
df.groupby('Id').aggregate(classification_logic)
# Type
# Id
# 14035 1
# 24259 2
将熊猫作为pd导入
将numpy作为np导入
#构造示例数据帧
df=pd.DataFrame()
df['Id']=['14035','14035','14035','24259','24259','
df['Type']=['A','B','C','A','B',]
#定义分类逻辑
def分类逻辑(类型列表):
如果set(['A','B','C'])尽管前面的解决方案往往有效,但我关心的是所使用的字符串连接
在以下情况下,此类字符串连接将无法对ID进行分类:
如果以未排序的方式连接字符,则后面的逻辑将无法对ID进行分类<代码>即:('BAC'!='ABC')
,即:('ABCD'!='ABC')
import pandas as pd
import numpy as np
# Construct sample dataframe
df = pd.DataFrame()
df['Id'] = ['14035', '14035', '14035', '24259', '24259', ]
df['Type'] = ['A', 'B', 'C', 'A', 'B', ]
# Define classification logic
def classification_logic(list_of_types):
if set(['A', 'B', 'C']) <= set(list_of_types):
return 1
if set(['A', 'B']) <= set(list_of_types):
return 2
return np.nan
# Apply to groups
df.groupby('Id').aggregate(classification_logic)
# Type
# Id
# 14035 1
# 24259 2
将熊猫作为pd导入
将numpy作为np导入
#构造示例数据帧
df=pd.DataFrame()
df['Id']=['14035','14035','14035','24259','24259','
df['Type']=['A','B','C','A','B',]
#定义分类逻辑
def分类逻辑(类型列表):
if set(['A','B','C'])的灵感来源于这里是一个稍微优化的版本:
In [66]: df.groupby('Id')['Type'] \
...: .agg(lambda x: 'Cat 1' if 'ABC' in ''.join(x.sort_values()) else 'Cat 2') \
...: .reset_index(name='Cat')
...:
Out[66]:
Id Cat
0 14035 Cat 1
1 24259 Cat 2
以下是一个稍微优化的版本:
In [66]: df.groupby('Id')['Type'] \
...: .agg(lambda x: 'Cat 1' if 'ABC' in ''.join(x.sort_values()) else 'Cat 2') \
...: .reset_index(name='Cat')
...:
Out[66]:
Id Cat
0 14035 Cat 1
1 24259 Cat 2
我会使用set
comparison使其不受顺序的影响
In [976]: df.groupby("Id")["Type"].apply(
...: lambda x: 'Cat 1' if set(x) == set('ABC') else
...: 'Cat 2' if set(x) == set('AB') else
...: 'Cat X')
Out[976]:
Id
14035 Cat 1
24259 Cat 2
Name: Type, dtype: object
我会使用set
comparison使其不受顺序的影响
In [976]: df.groupby("Id")["Type"].apply(
...: lambda x: 'Cat 1' if set(x) == set('ABC') else
...: 'Cat 2' if set(x) == set('AB') else
...: 'Cat X')
Out[976]:
Id
14035 Cat 1
24259 Cat 2
Name: Type, dtype: object
您好@C.Square,我尝试过这样做:testing_df=testing_df.groupby('Id',as_index=False)[“Type”]。聚合(分类逻辑)以不重置索引。但它正在把我还给Np.Nan。知道为什么吗?嗨@C.Square,我试过这样做:testing_df=testing_df.groupby('Id',as_index=False)[“Type”]。聚合(分类逻辑)以不重置索引。但它正在把我还给Np.Nan。知道为什么吗?