gpt4 book ai didi

python - 如何修改 Pandas 数据框中混合数据类型列中的数值?

转载 作者:行者123 更新时间:2023-12-04 08:39:17 25 4
gpt4 key购买 nike

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

  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
尽管它看起来像一项简单的任务,但我无法在互联网上的任何地方找到解决方案。
提前致谢。

最佳答案

首先你需要转换object将列输入到 numeric列使用 pd.to_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 ,您可以使用 df.fillna :
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

关于python - 如何修改 Pandas 数据框中混合数据类型列中的数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64640182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com