使用位置位置将单元格替换为值

2024-04-19 18:28:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下示例数据框:

ID Text  Value
A  yes      1
C  no       1

我想将第二行中与ID“C”关联的1值替换为0。我在联机找到的传统替换方法(使用.replace)会将两个1都替换为0

下面是我想要的数据集:

ID Text  Value
A  yes      1
C  no       0

Tags: 数据方法notextid示例value联机
3条回答

使用基于标签的索引.loc如何:

df.loc["C", "Value"] = 0

或者使用基于索引的.iloc

df.loc[1, "Value"] = 0

使用np.where

np.where(df.ID=='C',0,df.Value)
Out[260]: array([1, 0], dtype=int64)

因为你要求特别使用位置。有两种方法可以做到。使用lociloc(数字位置)

import pandas as pd

df = pd.DataFrame({'ID': ['A', 'C'],
                   'Text' : ['yes', 'no'],
                   'Value' : ['1', '1']
        }
        )

# set the id as index
df.set_index('ID', inplace=True)

# use index to raplace value
df.loc['C','Value'] = 0

# reset index
df.reset_index(inplace=True)


# same operation can be done using iloc
# as an example use numeric position to revert back
df.iloc[1, 2] = 1

相关问题 更多 >