【问题标题】:Panda Dataframe Series Replace value熊猫数据框系列替换值
【发布时间】:2022-06-24 00:41:57
【问题描述】:

我有一个 Python 程序:

import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')

# Read a CSV file:
name = pd.read_csv("users.csv", delimiter=";") 

# Get the value of the row with index 0, column "Name"
name = users.iloc[0].get("Name")

# Supposedly replace the first user Name to np.NaN
users.iloc[0].replace(name , np.NaN, inplace=True)

我希望这会替换名称,但事实并非如此。 替换它的方法是:

Replace every name "name" with np.NaN ?
users.replace(name, np.NaN, inplace=True)

但是上一行不是要替换整个文件的名称吗?如何只替换行?

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    当您对 df.iloc[i] 进行替换时,它不会持续返回到源数据框。这是一个例子:

    df = pd.DataFrame({'A': [1]})
    Out[1]: 
    A    1
    Name: 0, dtype: int64
    

    替换出现就可以了。

    df.iloc[0].replace(1, 5)
    Out[2]: 
    A    5
    Name: 0, dtype: int64
    

    但它实际上并没有被发送回原始数据帧。

    df
    Out[3]: 
       A
    0  1
    

    您需要将替换语句的输出重新分配回数据框中的正确位置。像这样的:

    df.iloc[0] = df.iloc[0].replace(1, 5)
    df
    Out[4]: 
       A
    0  5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 2022-01-11
      • 2019-10-12
      • 2020-06-03
      • 2019-02-02
      相关资源
      最近更新 更多