dataframe replace() 在函数内部不起作用。

huangapple go评论59阅读模式
英文:

dataframe replace() is not working inside function

问题

这个问题可能是因为在函数内部使用了 dfnx.replace({s,c},inplace=True),其中sc是两个字符串,但它们应该是两个单独的参数,而不是一个字典键值对。你可以尝试修改函数的相应部分如下:

dfnx.replace(s, c, inplace=True)

这样应该能够正确地替换字符串中的空格。如果仍然存在问题,请确保在函数内部处理数据框时,没有对原始数据框进行不必要的修改,以免影响函数的其他部分。

英文:

I was replacing some strings (removing whitespaces) inside multiple dataframes manually, then I decided to centralize this code inside a function as follows (the print statements are just for debugging):

def merge_multiword_teams(dfnx,team_lst):
    print(dfnx[dfnx['team'].str.contains('lazer')])
    for s in team_lst:
        c=s.replace(' ','')
        print(s + c)
        dfnx.replace({s,c},inplace=True)
        print(dfnx[dfnx['team'].str.contains('lazer')])
    return dfnx

then calling it

df = merge_multiword_teams(df,['Trail Blazers'])

the print statement shows that the whitespaces were not replaced

team W L W/L% GB PS/G PA/G SRS year
17 Portland Trail Blazers 49 33 0.598 16.0 105.6 103.0 2.6 2018
52 Portland Trail Blazers 41 41 0.5 26.0 107.9 108.5 -0.23 2017
79 Portland Trail Blazers 44 38 0.537 29.0 105.1 104.3 0.98 2016
109 Portland Trail Blazers 51 31 .622 102.8 98.6 4.41 2015
146 Portland Trail Blazers 54 28 .659 5.0 106.7 102.8 4.44 2014

Trail BlazersTrailBlazers
team W L W/L% GB PS/G PA/G SRS year
17 Portland Trail Blazers 49 33 0.598 16.0 105.6 103.0 2.6 2018
52 Portland Trail Blazers 41 41 0.5 26.0 107.9 108.5 -0.23 2017
79 Portland Trail Blazers 44 38 0.537 29.0 105.1 104.3 0.98 2016
109 Portland Trail Blazers 51 31 .622 102.8 98.6 4.41 2015
146 Portland Trail Blazers 54 28 .659 5.0 106.7 102.8 4.44 2014

what can be wrong with this approach ? given that moving the replace statement outside the function works perfectly

答案1

得分: 0

问题是你把sc放在了一个集合中,但我认为你可能想把它们作为字典({s:c})。

英文:

The problem is that you've put s and c as a set when I think you meant it as a dict ({s:c})

huangapple
  • 本文由 发表于 2023年7月13日 11:47:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76675766.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定