如何在基础搜索的项目上添加新列,例如,如果dataframe列包含BX,那么在新列中应将其替换为BOX,因为它有30多种缩写形式
我认为字典将是替换的最佳选择
mapping= {
'BX': 'BOX',
'CS': 'CASE',
'EA': 'EACH',
'PK': 'PACK',
'None': None
}
import pandas as pd
lst = ['BX', 'EA', 'EA', 'PK', 'BG','CS']
df = pd.DataFrame(lst)
df.map(mapping)
我无法做到
答案 0 :(得分:0)
您可以执行以下操作。
# first define a mapping
mapping= {
'BX': 'BOX',
'CS': 'CASE',
'EA': 'EACH',
'PK': 'PACK',
'None': None
}
# then apply it with map (assuming your abbreviations are
# stored in column short and the result should be stroed
# in long)
df['long']=df['short'].map(mapping)
具有以下测试数据框
lst = ['BX', 'EA', 'EA', 'PK', 'BG','CS']
df = pd.DataFrame(dict(short=lst))
df['short'].map(mapping)
它输出:
Out[447]:
short long
0 BX BOX
1 EA EACH
2 EA EACH
3 PK PACK
4 BG NaN
5 CS CASE
答案 1 :(得分:-1)
df
:import pandas as pd
import numpy as np
lst = ['BX', 'EA', 'EA', 'PK', 'BG','CS', np.NaN, None]
df = pd.DataFrame(lst, columns=['Data'])
mappings = {'BX': 'BOX',
'CS': 'CASE',
'EA': 'EACH',
'PK': 'PACK',
'BX': 'BOX',
None: None}
mappings
:df['new'] = df.Data.map(mappings)