我正在处理python项目,并获得了一个包含多列和多行的数据格式。
我想摆脱所有的一切,除了在每个单元格的数字数据。不使用循环就能做到这一点吗?
以下是数据中的一个示例:
a b c d e f g h
1 att-7 att-3 att-10 att-10 att-15 att-11 att-2 att-7
2 att-9 att-7 att-12 att-4 att-10 att-4 att-13 att-4
3 att-10 att-6 att-1 att-1 att-13 att-12 att-9 att-6 我想申请这样的东西:
def modify_string(cell):
return cell.str.extract(r'(\d+)')
df_modified = df.apply(lambda x: modify_string(x))这里有可能避免循环吗?什么是最有效的方式,因为数据相对较大?你将如何解决这个问题?
发布于 2022-06-02 13:07:57
使用applymap的第一种方法是按元素应用函数。它依赖于后面跟着“-”的数字。
df.applymap(lambda x: x.split('-')[-1])如果情况并非总是如此,您还可以使用str.extract并提取数字。
df.stack().str.extract(r'(\d+)',expand=False).unstack()输出:
a b c d e f g h
1 7 3 10 10 15 11 2 7
2 9 7 12 4 10 4 13 4
3 10 6 1 1 13 12 9 6发布于 2022-06-02 13:10:43
我将使用:https://pypi.org/project/pandarallel/和简单的应用函数。
https://stackoverflow.com/questions/72476355
复制相似问题