簡體   English   中英

替換熊貓數據框中大於數字的值

[英]Replacing values greater than a number in pandas dataframe

我有一個大數據框,它看起來像:

df1['A'].ix[1:3]
2017-01-01 02:00:00    [33, 34, 39]
2017-01-01 03:00:00    [3, 43, 9]

我想用 11 替換大於 9 的每個元素。

因此,上述示例所需的輸出是:

df1['A'].ix[1:3]
2017-01-01 02:00:00    [11, 11, 11]
2017-01-01 03:00:00    [3, 11, 9]

編輯:

我的實際數據框有大約 20,000 行,每行都有大小為 2000 的列表。

有沒有辦法為每一行使用numpy.minimum函數? 我認為它會比list comprehension方法更快?

很簡單: df[df > 9] = 11

您可以將applylist comprehension一起使用:

df1['A'] = df1['A'].apply(lambda x: [y if y <= 9 else 11 for y in x])
print (df1)
                                A
2017-01-01 02:00:00  [11, 11, 11]
2017-01-01 03:00:00    [3, 11, 9]

更快的解決方案是首先轉換為numpy array ,然后使用numpy.where

a = np.array(df1['A'].values.tolist())
print (a)
[[33 34 39]
 [ 3 43  9]]

df1['A'] = np.where(a > 9, 11, a).tolist()
print (df1)
                                A
2017-01-01 02:00:00  [11, 11, 11]
2017-01-01 03:00:00    [3, 11, 9]

您可以使用 numpy 索引,通過.values函數訪問。

df['col'].values[df['col'].values > x] = y

用 y 的值替換任何大於 x 的值。

因此,對於問題中的示例:

df1['A'].values[df1['A'] > 9] = 11

我知道這是一篇舊帖子,但DataFrame.where現在直接支持DataFrame.where 在你的例子中:

df.where(df <= 9, 11, inplace=True)

請注意,pandas 的wherenumpy.where不同。 在 Pandas 中,當condition == True ,使用數據幀中的當前值。 condition == False ,采用另一個值。

編輯:

您可以使用Series.where為一列實現相同的Series.where

df['A'].where(df['A'] <= 9, 11, inplace=True)

我來找一個解決方案,用 1 else 0 替換每個大於 h 的元素,它有一個簡單的解決方案:

df = (df > h) * 1

(這不能解決 OP 的問題,因為所有 df <= h 都被 0 替換。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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