我正在编写一个脚本来处理我可以重用的csv。现在我正在使用此代码来规范化csv文件中的列,以便它们都可以具有相似的列。
df = pd.read_csv('Crokis.csv', index_col=0, encoding = "ISO-8859-1", low_memory=False)
genCol=['Genus','genus','ngenus','genera',]
df.rename(columns={typo: 'Genus' for typo in genCol}, inplace=True)
spCol=['species', 'sp', 'Species']
df.rename(columns={typo: 'species' for typo in spCol}, inplace=True)
chromCol=['Chromosome count', 'chromosome', 'Cytology', '2n', 'Chromosome']
df.rename(columns={typo: 'chromosome' for typo in chromCol}, inplace=True)
del chromCol, spCol, genCol
它工作正常,但有2个问题
由于上/下外壳或在其正面或背面添加了其他字符,因此列表中缺少某些项目。有没有办法包含regex
或类似的东西来处理不同的变化?
似乎有一个多余的模式,所以我认为应该有一种方法来优化它。
答案 0 :(得分:2)
可以使用python re函数来执行此操作。
下面是一个示例,其中一个'genus.*'
替换为'Genus'
。
它将匹配并替换为例如'genUS'
,'GENUS'
,'Genus_666'
import pandas as pd
import re
df = pd.read_csv('Crokis.csv', index_col=0, encoding = "ISO-8859-1", low_memory=False)
# 'Genus' column renaming
f = lambda x: re.sub('genus.*','Genus', x, flags = re.IGNORECASE)
df.rename(columns = f, inplace = True)
答案 1 :(得分:0)
我会这样解决问题:
# use a single dict to hold the mapping
name_map = {'Genus': ['Genus','genus','ngenus','genera'],
'species':['species', 'sp', 'Species'],
'chromosome':['Chromosome count', 'chromosome', 'Cytology', '2n', 'Chromosome']}
col_translate = {}
for c in df.columns:
for canonical_name, alias_names in name_map.items():
for alias_name in alias_names:
if c.lower() == col_name.lower():
col_translate[c] = canonical_name
# if you want to check prefix or suffix...
elif c.startswith(alias_name) or c.endswith(alias_name)
col_translate[c] = canonical_name
# ... any additional, more complicated test
...
如果某些re
可能认为太难的情况