2024-06-02 06:24:58 发布
网友
我在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
虽然这看起来是一项简单的任务,但我在互联网上的任何地方都找不到解决方案
提前谢谢
要将列乘以10并保留非数值"nope",需要将列转换为数字数据类型,并将非数值替换为NaN。然后,您将对该列执行操作,并仅替换该列中以数字开头的值,而保留非数字值
"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列:
object
numeric
In [141]: df.col_2 = pd.to_numeric(df.col_2, errors='coerce')
errors='coerce'将列中的所有非数字类型值转换为NaN
errors='coerce'
然后,乘以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,可以使用^{}:
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
要将列乘以10并保留非数值
"nope"
,需要将列转换为数字数据类型,并将非数值替换为NaN
。然后,您将对该列执行操作,并仅替换该列中以数字开头的值,而保留非数字值首先,需要使用^{} 将
object
类型的列转换为numeric
列:errors='coerce'
将列中的所有非数字类型值转换为NaN
然后,乘以10:
如果要将} :
NaN
转换回nope
,可以使用^{相关问题 更多 >
编程相关推荐