python - Pandas 数据框 - 根据后缀转换选定的单元格值

标签 python pandas dataframe type-conversion

我有一个数据框如下:

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”列下的值除外 - 第一列):

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

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

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 - Pandas 数据框 - 根据后缀转换选定的单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75740088/

相关文章:

r - 对 r 中具有特定条件的行求和

python - 如何命名由 numpy 数组填充的数据框列?

python - 从字符串的开头到结尾匹配字符串

python - 如何让我的Regex函数识别更多子字符串

python - 美丽汤4 : Need to add inverse paragraphs tags to separate a field into two paragraphs

python - 用另一个列值填充缺失的日期

python - 如何识别数据框中与前一行相比的行中的字符串变化?

python - 无法安装 tensorflow 压缩

python - 无法将简单的文本文件转换为 pandas 数据框

python - Pandas 在 MultiIndex DataFrame 中选择特定的低级列