如何修改数据帧中混合数据类型列中的数值?

2024-06-02 06:24:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Pyton中有一个熊猫数据框,看起来像这样(我的实际数据框比这个大得多):

  col_1 col_2
0   0.8   0.1
1  nope   0.6
2   0.4   0.7
3  nope  nope

如何对特定列的数值执行某些操作。例如,将col_2的数值乘以10,得到如下结果:

  col_1 col_2
0   0.8   1
1  nope   6
2   0.4   7
3  nope  nope

虽然这看起来是一项简单的任务,但我在互联网上的任何地方都找不到解决方案

提前谢谢


Tags: 数据地方互联网col解决方案数值pytonnope
2条回答

要将列乘以10并保留非数值"nope",需要将列转换为数字数据类型,并将非数值替换为NaN。然后,您将对该列执行操作,并仅替换该列中以数字开头的值,而保留非数字值

numeric_col2 = pd.to_numeric(df["col_2"], errors="coerce")
df.loc[numeric_col2.notnull(), "col_2"] = numeric_col2 * 10

print(df)
  col_1 col_2
0   0.8     1
1  nope     6
2   0.4     7
3  nope  nope

首先,需要使用^{}object类型的列转换为numeric列:

In [141]: df.col_2 = pd.to_numeric(df.col_2, errors='coerce')

errors='coerce'将列中的所有非数字类型值转换为NaN

然后,乘以10:

In [144]: df.col_2 = df.col_2 * 10

In [145]: df
Out[145]: 
  col_1  col_2
0   0.8    1.0
1  nope    6.0
2   0.4    7.0
3  nope    NaN

如果要将NaN转换回nope,可以使用^{}

In [177]: df.fillna('nope', inplace=True)

In [178]: df
Out[178]: 
  col_1 col_2
0   0.8     1
1  nope     6
2   0.4     7
3  nope  nope

相关问题 更多 >