【发布时间】:2021-09-12 15:34:11
【问题描述】:
我有这个
df=pd.DataFrame({
'm':[16,23,24,26,17,18],
'A':['23-24','23-24','23-24','23-24','16-18','20']
})
我需要创建列 ['AC'],它根据列 ['m'] 从列 ['A'] 中获取一个值,如下所示:
if col['m'] = col['A'], then value from col['m']
if col['m'] =< col['A'] first value of the range, then the first value from col['A'] range
if col['m'] = is a value inside range displayed on col['A'], then value from col['m']
if col['m'] => col['A'] last value of the range, then last from col['A'] range
这是想要的结果:
m A AC
16 23-24 23
23 23-24 23
24 23-24 24
26 23-24 24
17 16-18 17
18 20 20
我尝试了下面的代码,但它不起作用
df[['a1','a2','a3']] = df['A'].str.split('-',expand=True)
df['a1']= df['a1'].replace([None],np.nan)
df['a1']= df['a1'].replace(np.nan,df.A)
df['a2']= df['a2'].replace([None],np.nan)
df['a2']= df['a2'].replace(np.nan,df.A)
df['a3']= df['a3'].replace([None],np.nan)
df['a3']= df['a3'].replace(np.nan,df.A)
df['a1']= pd.to_numeric(df['a1'], errors='coerce')
df['a2']= pd.to_numeric(df['a2'], errors='coerce')
df['a3']= pd.to_numeric(df['a3'], errors='coerce')
conds = [
(df['m']<= df['a1']),
(df['m']> df['a1']),
(df['m']> df['a1'])&(df['m']< df['a2'])]
choices = [df['a1'],df['a2'],df['a3']]
df['AC'] = np.select(conds, choices)
【问题讨论】:
标签: python pandas conditional-statements range