【问题标题】:Python Pandas dataframe modify column value based on function that cleans string value and assign to new columnPython Pandas数据框根据清除字符串值并分配给新列的函数修改列值
【发布时间】:2020-03-11 16:22:04
【问题描述】:

我有一些数据要清理,我想删除一些键,其中键有六个前导零,如果键不以“ABC”结尾或不以“DEFG”结尾,那么我需要清理最后 3 个索引中的货币代码。如果键不以前导零开头,则直接返回键。

为此,我编写了一个处理字符串的函数,如下所示:

def cleanAttainKey(dirtyAttainKey):

    if dirtyAttainKey[0] != "0":
        return dirtyAttainKey
    else:
        dirtyAttainKey = dirtyAttainKey.strip("0")

    if dirtyAttainKey[-3:] != "ABC" and dirtyAttainKey[-3:] != "DEFG":
        dirtyAttainKey =  dirtyAttainKey[:-3]
    cleanAttainKey = dirtyAttainKey
    return cleanAttainKey

现在我构建了一个虚拟数据框来测试它,但它报告错误:

  1. 数据框
df = pd.DataFrame({'dirtyKey':["00000012345ABC","0000012345DEFG","0000023456DEFGUSD"],'amount':[100,101,102]},
                  columns=["dirtyKey","amount"])
  1. 我需要在 df 中获取一个名为“cleanAttainKey”的新列,然后使用“cleanAttainKey”函数修改“dirtyKey”中的每个值,然后将清理后的密钥分配给新列“cleanAttainKey”,但是看起来pandas 不支持这种类型的修改。
# add a new column in df called cleanAttainKey
df['cleanAttainKey'] = ""
# I want to clean the keys and get into the new column of cleanAttainKey
dirtyAttainKeyList = df['dirtyKey'].tolist()
for i in range(len(df['cleanAttainKey'])):
    df['cleanAttainKey'][i] = cleanAttainKey(vpAttainKeyList[i])

我收到以下错误消息:

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

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

结果应该和下面的df2一样:

df2 = pd.DataFrame({'dirtyKey':["00000012345ABC","0000012345DEFG","0000023456DEFGUSD"],'amount':[100,101,102],
                  'cleanAttainKey':["12345ABC","12345DEFG","23456DEFG"]},
                  columns=["dirtyKey","cleanAttainKey","amount"])
df2

有没有更好的方法来修改脏键并在 Pandas 中使用干净键获得一个新列? 谢谢

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    这是罪魁祸首:

    df['cleanAttainKey'][i] = cleanAttainKey(vpAttainKeyList[i])
    

    当您使用 extract 数据框时,Pandas 保留选择制作副本或视图的能力。如果你只是读取数据没关系,但这意味着你永远不应该修改它。

    惯用的方式是使用loc(或iloc[i]at):

    df.loc[i, 'cleanAttainKey'] = cleanAttainKey(vpAttainKeyList[i])
    

    (以上假设为自然范围索引...)

    【讨论】:

    • 嗨,Serge,如果我按上述方式输入数据框,那么您的解决方案有效。但是,就我而言,我使用 pd.read_excel() 来加载 excel 文件,在这种情况下,即使使用 df.loc,我仍然会收到错误消息:TypeError: 'int' object is not subscriptable跨度>
    • @commentallez-vous:那么这是一个不同的问题。您应该检查引发错误的行。它应该包含一个您希望成为列表(或系列、字典或数据框)的变量,并且只是一个 int。我猜不出更多。如果你不能解决它,你应该考虑用完整的堆栈跟踪和足够的数据来提出一个新问题。
    • 好的,非常感谢,看来是我写的函数的问题,让我先检查一下。
    • 知道了,加dirtyAttainKey = str(dirtyAttainKey)就解决了,再次感谢
    • @commentallez-vous:请不要忘记接受答案,以表明您不再需要这里的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 2020-03-19
    • 2020-05-23
    • 2017-10-21
    相关资源
    最近更新 更多