我有一个数据框如下:
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/