Pandas版的“如果是真的,就在这里,如果是假的,就在某处等着看

2024-09-28 05:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一个大数据集及其处理从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中查找{}。在

任何帮助都将不胜感激!在


Tags: themaptypecmcolprodmlpackaging
3条回答

类似于@Erfan的答案,使用^{},但跳过melt来使用^{}。 根据问题中的变量:

In []: df['ITEM'] = pd.np.where(df.PROD_TYPE == "PK",
                                df.PKG_TYPE.map(pack_dict),
                                df.PROD_TYPE.map(prod_dict))

In []: df
Out[]:
  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

注意,numpy已经由pandas加载,只需使用pd.np。在

这就是我解决这个问题的方法:

# First we make two dataframes out of the dictionaries with pd.melt
df2 = pd.DataFrame(prod_dict, index=[0])
df3 = pd.DataFrame(pack_dict, index=[0])

df2 = df2.melt(var_name=['PROD_TYPE'], value_name = 'ITEM')
df3 = df3.melt(var_name=['PKG_TYPE'], value_name = 'ITEM')

# df2
    PROD_TYPE   ITEM
0   PK          Packaging
1   ML          Mix
2   CM          Textile
3   NK          Metallic

# df3
    PKG_TYPE    ITEM
0   PK3         Misc Packaging
1   PK4         Mix Packaging
2   PK9         Textile Packaging

# Now we can merge our information together on keycolumns PROD_TYPE and PKG_TYPE
df_final = pd.merge(df, df2, on='PROD_TYPE')
df_final = pd.merge(df_final, df3, on='PKG_TYPE')

    PROD_TYPE   PKG_TYPE    VALUE   ITEM_x      ITEM_y
0   PK          PK3         1000    Packaging   Misc Packaging
1   ML          PK4         900     Mix         Mix Packaging
2   ML          PK4         800     Mix         Mix Packaging
3   CM          PK9         700     Textile     Textile Packaging

# Finally we use np.where to conditionally select the values we need 
df_final['ITEM'] = np.where(df_final.PROD_TYPE == 'PK', df_final.ITEM_y, df_final.ITEM_x)

# Drop columns which are not needed in output
df_final.drop(['ITEM_x', 'ITEM_y'], axis=1, inplace=True)

输出

^{pr2}$

np.where来自numpy模块,工作原理如下:
np.where(condition, true value, false value)

一种方法是:

df["ITEM"]= [pack_dict[row[1]["PKG_TYPE"]] 
    if row[1]["PROD_TYPE"] == "PK"     
    else     prod_dict[row[1]["PROD_TYPE"]] 
    for row in df.iterrows()]

我发现这比Erfan的解决方案快10倍。在

相关问题 更多 >

    热门问题