[英]How to compare just the date or just date time ignoring seconds in a Python Pandas dataframe column of mixed data types?
[英]How to modify numercial values in a column of mixed data types in a pandas dataframe?
我在 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
尽管它看起来像一项简单的任务,但我无法在互联网上的任何地方找到解决方案。
提前致谢。
首先,您需要使用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
要将您的列乘以 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.