我试图将一个大数据集及其处理从Excel转换到Python/Pandas,当我试图实现Pandas版本的“IF(col a=x,VLOOKUP(表Y中的col B),否则,VLOOKUP(表Z中的col a))”时遇到了一个障碍。在
我已经创建了两个单独的字典,它们将作为pandas版本的表Y和Z,但是我还没有找到一个构造来告诉pandas使用B列中的值来查找字典。在
在熊猫身上尝试:
# Created a function to map the values from
# PROD_TYPE to the prod_dict.
def map_values(row, prod_dict):
return prod_dict[row]
# Created the dictionaries / old VLOOKUP tables.
prod_dict = {'PK': 'Packaging',
'ML': 'Mix',
'CM': 'Textile',
'NK': 'Metallic'}
pack_dict = {'PK3' : 'Misc Packaging',
'PK4' : 'Mix Packaging',
'PK9' : 'Textile Packaging'}
df = pd.DataFrame({'PROD_TYPE' : ['PK', 'ML', 'ML', 'CM'],
'PKG_TYPE': ['PK3', 'PK4', 'PK4', 'PK9'],
'VALUE': [1000, 900, 800, 700]})
# Apply the map_values function.
df['ITEM'] = df['PROD_TYPE'].apply(map_values, args = (prod_dict,))
我得到:
^{pr2}$当我要找的是:
PROD_TYPE PKG_TYPE VALUE ITEM
0 PK PK3 1000 Misc Packaging
1 ML PK4 900 Mix
2 ML PK4 800 Mix
3 CM PK9 700 Textile
或者,更清楚地说:如果PROD_TYPE
是'PK'
,请从pack_dict
中的PKG_TYPE
列中查找该值;否则,在prod_dict
中查找{
任何帮助都将不胜感激!在
类似于@Erfan的答案,使用^{} ,但跳过} 。
根据问题中的变量:
melt
来使用^{注意,
numpy
已经由pandas
加载,只需使用pd.np
。在这就是我解决这个问题的方法:
输出
^{pr2}$np.where
来自numpy
模块,工作原理如下:np.where(condition, true value, false value)
一种方法是:
我发现这比Erfan的解决方案快10倍。在
相关问题 更多 >
编程相关推荐