【问题标题】:Python Pandas Commands .replace() Not Working despite inplace = TruePython Pandas 命令 .replace() 尽管 inplace = True 仍不工作
【发布时间】:2021-04-20 01:37:24
【问题描述】:

我正在尝试在由 .read_excel() 制成的 DataFrame 上使用 .replace()。尽管使用了 inplace = True,并且对拼写进行了三次检查(从原始 excel 文档中复制粘贴),该命令仍无法正常工作

import pandas as pd

def create_frame(path):
    df1 = pd.read_excel(path)
    return df1.replace(('Visit 2: Day 1','Day 1'), inplace = True)

df = create_frame('example.xlsx')
df.to_csv('test.csv')

我也尝试过使用 df2 = df1.replace(('Visit 2: Day 1','Day 1')) 而不是 inplace = True,但测试 csv 总是带有“访问 2:第 1 天”

.sort_values.reset_index 也有类似的功能障碍(命令不起作用)。

任何想法我做错了什么?感谢所有帮助!谢谢!

【问题讨论】:

  • 如果您在replace 中使用inplace = True,那么它将返回None,并且您的to_replace 参数似乎格式错误,您究竟要替换什么?

标签: python pandas


【解决方案1】:

您可以在没有inplace=True 的情况下创建函数create_frame

如果你使用inplace=True,它将从函数create_frame返回None

同样,Pandas dataframe: set_index with inplace=True returns a NoneType, why??

import pandas as pd

def create_frame(path):
    df1 = pd.read_excel(path)
    return df1.replace(('Visit 2: Day 1','Day 1'))

df = create_frame('example.xlsx')
df.to_csv('test.csv')

当你使用df2 = df1.replace(('Visit 2: Day 1','Day 1'))时,它不会影响df1

所以不使用func,你可以这样做:

df1 = pd.read_excel(path)
df2 = df1.replace(('Visit 2: Day 1','Day 1'))
df2.to_csv('test.csv')

df1 = pd.read_excel(path)
df1.replace(('Visit 2: Day 1','Day 1'), inplace=True)
df1.to_csv('test.csv')

【讨论】:

    猜你喜欢
    • 2022-10-18
    • 2019-05-07
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 2017-08-08
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多