尝试根据某些字符串是否出现在不同的列中来填充数据帧中的列。我可以使用一系列嵌套的np.where语句来实现这一点,例如:
cond1=df.CollectType.str.contains('Outcrop')
cond2=df.CollectType.str.contains('Chip channel')
cond3=df.CollectType.str.contains('Rubble')
cond4=df.CollectType.str.contains('Float')
cond5=df.CollectType.str.contains('Dump')
df['R_SampleType'] = np.where(cond1, 'Outcrop', np.where(cond2,
'Chip channel', np.where(cond3,'Rubble',
np.where(cond4,'Float',
np.where(cond5,'Dump','')))))但这似乎并不是很有效。因此,我尝试列出条件,并使用以下命令调用该列表:
values = ['Outcrop', 'Chip Channel','Rubble','Float','Dump']
conditions = list(map(df['CollectType'].str.contains, values))
df['R_SampleType'] = np.select(conditions, values, '')但是我得到了一个错误:
ValueError: invalid entry 0 in condlist: should be boolean ndarray有什么建议吗?
发布于 2021-04-07 03:37:32
看起来您只是想复制一列,并在不满足条件的地方放置一个空字符串。
如果是这样的话,这里有一个解决方案:
df["R_SampleType"] = df.CollectType.where(df.CollectType.isin(values_ok), other="")可重现的例子:
from random import choices
values_ok = ["Outcrop", "Chip channel", "Rubble", "Float", "Dump"]
values_nok = ["Not", "A", "Valid", "Value"]
num_items = 15
df = pd.DataFrame(
choices(values_ok + values_nok, k=num_items), columns=["CollectType"]
)
df["R_SampleType"] = df.CollectType.where(df.CollectType.isin(values_ok), other="")https://stackoverflow.com/questions/66974996
复制相似问题