pandas练习-map

2019-12-22  本文已影响0人  酸甜柠檬26

map有三种用法:
1、对每个元素操作
2、根据字典修改元素的值
3、根据dataframe修改元素的值
2和3可视为一种

Question:

用另一个dataframe的值替换当前dataframe的值

一个df1,里边存储着英文的蔬菜名,有另外一个df2,里边存储着蔬菜名和对应的大类别,要求按照df2的蔬菜名和大类别对应关系给df1的蔬菜名重新赋值。
注意:如果df2中没有df1中的蔬菜名那么蔬菜1保留原值;
如果df2中对应的大类别为空,那么df1中的蔬菜名保持原值;
其他情况进行替换。

import pandas as pd
df1 = pd.DataFrame({'ItemType1':['redTomato','whitePotato','yellowPotato','greenCauliflower','yellowCauliflower','yelloSquash',
'redOnions','YellowOnions','WhiteOnions','yellowCabbage','GreenCabbage']})
df2 = pd.DataFrame({'ItemType2':['whitePotato','yellowPotato','redTomato','yellowCabbage','GreenCabbage','yellowCauliflower','greenCauliflower',  
'YellowOnions','WhiteOnions','yelloSquash','redOnions'],
'newType':['Potato','Potato','Tomato','','','yellowCauliflower','greenCauliflower','Onions','Onions','Squash','Onions']})

#方法一:根据map+字典映射
#将df2中的两列转化成字典
df2['map_1'] = df2.apply(lambda x: {x['ItemType2']:x['newType']} if x['newType'] else {x['ItemType2']:x['ItemType2']},axis=1)
#将上面得到的一列小字典们转化成一个大字典new_dict
new_dict = {}
for dict1 in df2['map_1'].tolist():
    for k,v in dict1.items():
        if k not in new_dict:
            new_dict[k] = v
        else:
            new_dict[k].append(v)
#字典构造完毕,然后map,利用字典进行映射
df1['ItemType1'] = df1['ItemType1'].map(new_dict)
print(df1)

#方法二:根据map+Series
df2 = df2.set_index('ItemType2')#此刻将df2转化成了Series,Series被认为是一个长度固定且有序的字典,因为它将索引值和数值按位置配对
df2.loc[df2['newType'] == '','newType'] = df2.loc[df2['newType'] == ''].index #newType列中为‘’所在的行及newTpye列的数据=newType列为‘’所在行的索引,索引相当于key
df1['ItemType1'] = df1['ItemType1'].map(df2.newType)#同上面的利用字典进行映射的方法一样,只不过是直接将df2作为字典
print(df1)

#方法三:
#这是对df进行循环,不建议用
for r1 in range(df1.shape[0]):
    for r2 in range(df2.shape[0]):
        if df1.iloc[r1,0] == df2.iloc[r2,0]:
            if df2.iloc[r2,1] != '':
                df1.iloc[r1,0] = df2.iloc[r2,1]
            else:
                df1.iloc[r1,0] = df1.iloc[r1,0]
print(df1)

用一个字典中的值替换当前dataframe的值

~该例子给的直接是个字典,比上面的更简单一点
在df中新增一列,该列为df中‘食物’列中的大类

import pandas as pd
df = pd.DataFrame({'食物':['苹果','橘子','黄瓜','番茄','五花肉'],
               '价格':[7,5,4,3,12],
               '数量':[5,8,3,4,2]})
map_dict = {
    '苹果':'水果',
    '橘子':['水果'],
    '黄瓜':'蔬菜',
    '番茄':'蔬菜',
    '五花肉':'肉类'
}

df['分类'] = df['食物'].map(map_dict)
print(df)

同一个dataframe里根据某列值更改另一列的值

Question:
要求评价不为null的时候是否有评价标记为1,否则标记为0

import pandas as pd
df = pd.DataFrame(
    {"has_comment_or_not":['0','0','0','1','0','0'],
    "comment_status":["null","null","120047007","null","null","122121"]}
    )

#方法一:对列直接进行修改,设定lambda函数
df['has_comment_or_not'] = df['comment_status'].map(lambda x: 0 if x == 'null' else 1)
print(df)

#方法二:函数,apply+def
def change_status(s):
    if s == 'null':
        return 0
    else:
        return 1
df['has_comment_or_not'] = df['comment_status'].apply(lambda x:change_status(x))
print(df)

方法三:进行条件筛选
df.loc[df['comment_status'] == 'null','has_comment_or_not'] = 0
df.loc[~(df['comment_status'] == 'null'),'has_comment_or_not'] = 1
print(df)
上一篇下一篇

猜你喜欢

热点阅读