我在pyhton中有一个熊猫数据框,看起来像这样(我的实际数据框比这个大得多):
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
尽管这看起来很简单,但我在互联网上的任何地方都找不到解决方案。
谢谢。
答案 0 :(得分:1)
首先,您需要使用pd.to_numeric
将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
,可以使用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
答案 1 :(得分:1)
要将列乘以10并保留非数字值"nope"
,则需要将列转换为数字dtype,然后将非数字值替换为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