python - Pandas数据框将N个小数后的数字替换为空字符串
问题描述
我正在学习如何在熊猫数据框替换中使用正则表达式。我遇到了以下问题:
我正在尝试将 N 个小数点后的字符串替换为空。例如12.349 ==> 12.35
。
MWE
import numpy as np
import pandas as pd
import seaborn as sns
df1 = pd.DataFrame({'A': ['hello','wold'],
'B': [12.346789, 12.223344]})
df1 = df1.astype(str)
round_ = 2
to_replace = r"(^\d+\." + r"\d" * round_ + r")(.*)"
repl = lambda m: m.group(0)
df1 = df1.replace(to_replace,repl,regex=True)
df1
Pandas 文档说我可以使用正则表达式来替换字符串,但是当我使用它时,我得到了函数 repr 而不是值。如何解决问题?
更新
我试图应用格式来转置数据帧。(当然我可以在转换之前设置样式,但是由于某些原因我需要应用格式来转置)。
df1 = pd.DataFrame({'A': ['hello','wold'],
'B': [12.349, 12.22]})
df1 = df1.T
df1.style.format({'B': "{:.2f}"}, axis=0)
参考
解决方案
你可以试试这个模式:
df1 = df1.replace(r"^(\d+\.\d{," + rf"{round_}" + r'})(\d*)',r'\1',regex=True)
输出:
survived pclass age sibsp parch fare
count 891.0 891.0 714.0 891.0 891.0 891.0
mean 0.38 2.30 29.69 0.52 0.38 32.20
std 0.48 0.83 14.52 1.10 0.80 49.69
min 0.0 1.0 0.42 0.0 0.0 0.0
25% 0.0 2.0 20.12 0.0 0.0 7.91
50% 0.0 3.0 28.0 0.0 0.0 14.45
75% 1.0 3.0 38.0 1.0 0.0 31.0
max 1.0 3.0 80.0 8.0 6.0 512.32
推荐阅读
- c++ - Meta Mixin.. 那是一回事吗?(模板元编程)
- azure-cosmosdb - 在 Gremlin 中,如何通过其中一个元素的属性对元素对进行分组?
- arrays - 迭代对象Angular 6内的数组
- ruby-on-rails - Rails 太阳黑子/Solr 索引不同步
- java - 如何禁用 Gradle 组中的所有任务?
- c - 使用信号量编译但未运行的生产者-消费者代码
- java - 使用 JNDI 从 LDAP 服务器搜索(选择)任何数据
- javascript - 从函数内部的 if 语句调用函数
- textview - Android TextView 文本选择
- python - 根据来自其他数据框的列上的多个条件创建数组值列