我有一个数据框如下。我想要的是生成另一列(freq
) 其中行将根据以下逻辑具有值:
-
If Mode列值以数字开头m
,然后填写数字n
in the freq column.
- m: 1, n: 12
- m: 6, n: 4
- m: 7, n: 2
- m: 8, n: 1
数据框
Mode
0 602
1 603
2 700
3 100
4 100
5 100
6 802
7 100
8 100
9 100
10 100
这是我尝试实现的逻辑。但不知怎的,它似乎不起作用。即使您可以建议一些替代解决方案,而不使用我的代码,那也可以。
def check_mode(Mode):
freq = ''
if (Mode.str.startswith('8')).any():
freq = 1
elif (Mode.startswith("7")).all():
freq = 2
elif (Mode.startswith("6")).any():
freq = 4
elif (Mode.startswith("1")).any():
freq = 12
return freq
df['freq']=check_mode(df_ia['Mode'].values)
一些观察
如果我使用:
if (Mode.str.startswith('8')).any():
我收到错误:
AttributeError: 'numpy.ndarray' object has no attribute 'str'
如果我使用:
if (Mode.startswith('8')).any():
我收到:
AttributeError: 'numpy.ndarray' object has no attribute 'startswith'
任何帮助都感激不尽。谢谢。
这就是你所追求的吗?
打印(df1)
Mode
0 602
1 603
2 700
3 100
4 100
5 100
6 802
7 100
8 100
9 100
10 100
c=[df1['Mode'].astype(str).str.startswith('8'),df1['Mode'].astype(str).str.startswith('7'),df1['Mode'].astype(str).str.startswith('6'),df1['Mode'].astype(str).str.startswith('1')]
ch=[1,2,4,12]
df1['newcol']=np.select(c, ch,0)
outcome
Mode newcol
0 602 4
1 603 4
2 700 2
3 100 12
4 100 12
5 100 12
6 802 1
7 100 12
8 100 12
9 100 12
10 100 12
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)