【发布时间】:2018-09-19 09:09:47
【问题描述】:
如何创建一个映射到字典的新数据框列,但仅适用于空白行,同时保留非空白行的引用列的值?下面我通过将“col1”映射到 x 创建了“新 col”,但我希望仅在“col2”为空的情况下映射到 x,否则使用 col2 中的值。
import pandas as pd
x = {'three':'green','four':'purple','five':'orange'}
d = {'col1': ['three', 'four', 'five'], 'col2':['blue',"","red"]}
df = pd.DataFrame(data=d)
df['new col']=df['col1'].map(x)
实际结果:
col1 col2 new col
0 three blue green
1 four purple
2 five red orange
期望的结果(新的 col 保留第 0 行和第 2 行中的值 'blue' 和 'red',但将第 1 行映射到 x):
col1 col2 new col
0 three blue blue
1 four purple
2 five red red
【问题讨论】: