我有一个如下的数据框架:

data_dict = {'id': {0: 'G1', 1: 'G2', 2: 'G3'},
 'S': {0: 35.74, 1: 36.84, 2: 38.37},
 'A': {0: 8.34, 1: '2.83%', 2: 10.55},
 'C': {0: '6.63%', 1: '5.29%', 2: 3.6}}
df = pd.DataFrame(data_dict) 

如果数据框中的所有值以%结尾,我想将它们乘以10000(列‘id’-第1列除外):

cols = df.columns[1:]
for index, row in df.loc[:, df.columns != 'id'].iterrows():
    for c in cols:
        if str(row[c]).endswith('%'):
            data_value = str(row[c])
            data_value = data_value.replace('%',"")
            df.at[index,c]= float(data_value) * 10000

最后,将所有列值(第一列除外)设置为NUMERIC:

df[cols[1:]] = df[cols[1:]].apply(pd.to_numeric, errors='coerce')

有没有一种简单的方法来转换值而不是迭代行?

推荐答案

我会使用一个定制函数:

def pct_to_float(s, factor=10000):
    s2 = s.astype(str)
    m = s2.str.endswith('%')
    return (s.mask(m, pd.to_numeric(s2.str.rstrip('%'), errors='coerce')*factor)
             .convert_dtypes()
            )

df[cols] = df[cols].apply(pct_to_float)

# to set the factor during the call
df[cols] = df[cols].apply(pct_to_float, factor=10000)

输出:

   id      S        A        C
0  G1  35.74     8.34  66300.0
1  G2  36.84  28300.0  52900.0
2  G3  38.37    10.55      3.6

Python相关问答推荐

try 从网站获取表(ValueRight:如果使用所有纯量值,则必须传递索引)

重命名变量并使用载体中的字符串存储 Select 该变量

从收件箱获取特定列中的重复行

已安装' owiener ' Python模块,但在导入过程中始终没有名为owiener的模块

如何获取Django REST框架中序列化器内部的外卡属性?

如何将Matplotlib的fig.add_axes本地坐标与我的坐标关联起来?

使用图片生成PDF Django rest框架

如何销毁框架并使其在tkinter中看起来像以前的样子?

拆分pandas列并创建包含这些拆分值计数的新列

在Python中为变量的缺失值创建虚拟值

Pythind 11无法弄清楚如何访问tuple元素

Polars比较了两个预设-有没有方法在第一次不匹配时立即失败

Excel图表-使用openpyxl更改水平轴与Y轴相交的位置(Python)

从groupby执行计算后创建新的子框架

我们可以为Flask模型中的id字段主键设置默认uuid吗

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

用渐近模计算含符号的矩阵乘法

如何禁用FastAPI应用程序的Swagger UI autodoc中的application/json?

处理具有多个独立头的CSV文件

如何获取Python synsets列表的第一个内容?