在将两种类型数据合并的时候,由于版本不同导致某一列中取值不同,因此在行转列进行统计的时候先要对齐。修改列值时使用了两种方法:
Map字典映射
首先想到的是将上图的关系用字典表示出来
dict = {'1': '05', '2': '02', '3': '01', '4': '04', '5': '07', '6': '06', '7': '07'}
# map可以作用于Series每一个元素的,是Series不是dataFrame
df['type'] = df['type'].map(dict)
df.head()
但是最后把图中左边列的数都变成了nan,应该时dict需要写全,不更改的值也要写出来,即dict加上{‘01’: ‘01’,‘02’:‘02’}…
if else 嵌套重新赋值
显而易见,注意括号不要写漏即可。
df['type'] = df['type'].apply(
lambda x: '05' if x == '1'else (
'02' if x == '2' else (
'01' if x == '3' else (
'04' if x == '4' else (
'07' if x == '5' else (
'06' if x == '6' else (
'03' if x == '7' else x)))))))
df.head()