Python -根据来自另一个单元格的数据将值赋给新的col时遇到麻烦



我的数据看起来像;

ID    File
1     this_file_whatever.ext1
2     this_whatever.ext2
3     this_is_ok_pooh.ext3

我正试图获得扩展名,并根据File中的扩展名将字典中的键放在新的col中。

def create_filegroups(row):
filegroup_dict = {
'GroupA': 'ext1',
'GroupB': 'ext2',
'GroupC': 'ext3'
}
if '.' in row['Name']:
test = row['Name'].split(".",1)[1]
return test
DF = build_df()
DF['COL3'] = DF.apply(create_filegroups(row), axis=1)
print(DF)
我不知道我做错了什么。当我到达那里时,我可以做字典比较,但我似乎不能对单元格应用函数。

我相信你需要pandas.Series.mapFile列中提取文件扩展名后,

试试这个:

df['COL3']= (
df['File']
.str.extract(r'w+.(w+)', expand=False)
.map({k:v for v,k in filegroup_dict.items()})
)

#输出:

print(df)
ID                     File    COL3
0   1  this_file_whatever.ext1  GroupA
1   2       this_whatever.ext2  GroupB
2   3     this_is_ok_pooh.ext3  GroupC

最新更新