Replace column values using a mapping-logic in pandas (problem with implementing a function)(在PANDA中使用映射逻辑替换列值(实现函数的问题))
本文介绍了在PANDA中使用映射逻辑替换列值(实现函数的问题)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下数据框。我想要的是生成另一列(freq
),其中的行将根据以下逻辑具有值:
如果模式列值以数字
m
开头,则在频率列中填写数字n
。- m: 1, n: 12 - m: 6, n: 4 - m: 7, n: 2 - m: 8, n: 1
DataFrame
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'
任何帮助都将不胜感激。谢谢。
推荐答案
试试这个。一个线条。
df['freq'] = df.Mode.astype(str).str.get(0).replace({'8': 1, '7': 2, '6': 4, '1': 12})
现在让我们解开它的用途:
# You can run this cell and check the result as well
(df.Mode.astype(str) # convert the column "Mode" into str data type
.str.get(0) # get string based methods and access the get
# method to get the 1st (`.get(0)`) digit
# replace the digits with a dictionary that
# maps to their replacement values.
.replace({'8': 1, '7': 2, '6': 4, '1': 12}))
df = pd.DataFrame([602, 603, 700, 100, 100, 100, 802, 100, 100, 100, 100,], columns=['Mode'])
df['freq'] = df.Mode.astype(str).str.get(0).replace({'8': 1, '7': 2, '6': 4, '1': 12})
df
## Output
# Mode freq
# 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
这篇关于在PANDA中使用映射逻辑替换列值(实现函数的问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在PANDA中使用映射逻辑替换列值(实现函数的问题)


猜你喜欢
- 我如何透明地重定向一个Python导入? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01