簡體   English   中英

替換 dataframe 系列中的值(int64)

[英]Replacing a value (int64) in series of dataframe

我嘗試使用下面的代碼將“new_col”的值從 3 更改為 1。首先,隨機矩陣是用索引 ['a','b'] 和列名 [x1~x5] 生成的,然后我另外添加了“new_col”。

我需要通過 'x1' 列調用該行,因此我運行df[df['x1']==val] ,然后我想我可以通過運行df[df['x1']==val]['new_col'] = 1來簡單地轉換 'new_col' 的值df[df['x1']==val]['new_col'] = 1

import pandas as pd
import numpy as np


df = pd.DataFrame(np.random.randint(0,10, size = (2,5)), index = ['a','b'], columns = ['x1','x2','x3','x4','x5'])

df['new_col'] = [3,1]

val = df['x1'].iloc[0]

df[df['x1']==val]['new_col'] = 1
display(df)

但是,它不會改變任何有錯誤的東西

__main__:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

您的方法接近解決方案,但需要稍微更改語法以避免警告。

您可以使用.loc和 boolean 索引作為第一個參數進行過濾,將列名作為第二個參數,如下所示:

df.loc[df['new_col']==3, 'new_col'] = 1

演示

print(df)

   x1  x2  x3  x4  x5  new_col
a   3   7   9   8   8        3
b   4   5   9   0   7        1

df.loc[df['new_col']==3, 'new_col'] = 1

   x1  x2  x3  x4  x5  new_col
a   3   7   9   8   8        1
b   4   5   9   0   7        1

編輯

根據評論的更新要求:

我真正需要做的是,首先找到 'x1' ==4 的行(在您的解決方案中),然后相應地更改該行中的 new_col 。

我們可以用:

df.loc[df['x1']==4, 'new_col'] = 1

我不知道這是否是您正在尋找的,但這可能是一個解決方案:

df["new_col"] = np.where(df["x1"]==val,1,df["new_col"])

所以對於每個 position,其中 x1 列中的行 == val,返回 1; 否則返回 new_col 的值

暫無
暫無

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

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