簡體   English   中英

如何修改熊貓數據框中混合數據類型列中的數值?

[英]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_numericobject類型列轉換為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

如果你要轉換NaNnope ,你可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM