首页 > 解决方案 > 熊猫数据框替换不替换值

问题描述

我写了一个代码,在单元格中取值,更改它,它应该用新值替换该单元格中的值。我有.replace适合虚拟数据框的功能,它可以工作,但对于我的示例它不起作用。旧值和新值是很长的字符串。我试过有inplace=True和没有它。

我的目标是改变ServiceDirection价值。

您可以从这里下载数据:

https://www.sendspace.com/file/7soufd

旧值如下所示: ...ype=1|ServiceDirection=2|CmtsMdIfIn...

新值如下所示: ype=1|ServiceDirection=DS|CmtsMdIfIn

这是代码:

data = pd.read_csv('data.csv')

def third_task():

    new_data = data

    for column in data:

        for row in data[column]:

            if 'ServiceDirection=1' in str(row):

                new_row = str(row).replace('ServiceDirection=1', 'ServiceDirection=DS')
                new_data = data.replace(str(row), new_row)

            elif 'ServiceDirection=2' in str(row):

                new_row = str(row).replace('ServiceDirection=2', 'ServiceDirection=US')
                new_data = data.replace(str(row), new_row)


    export_csv = new_data.to_csv(r'C:\Users\Pc\Desktop\export_dataframe1.csv', index = None, header=False)

    return new_data

print(third_task())

我也尝试过这样做:

df.replace(row, result)

而不是这个: data[column] = data[column].replace(str(row), str(result), inplace=True)

但仍然不起作用,它总是返回具有旧值的数据框

标签: pythonpandas

解决方案


我不知道您是否正在尝试构建数据。如果是这样,我就是这样做的。

df = pd.read_csv('data.csv', sep = '|', header = None)
df.columns = df.iloc[0, :].apply(lambda x: x.split('=')[0])
df = df.apply(lambda x: x.str.split('=').str.get(1))
df.head()

    ServiceSlaDelayPkts ServiceTimeCreated  CmtsMdIfName    ServiceSlaDropPkts  ServiceGateId   ServiceClassName    CmtsSysUpTime   ServicePktsPassed   ServiceIdentifier   ServiceDsMulticast  ... ServiceTimeActive   CmMacAddr   ServiceOctetsPassed ServiceAppId    CmtsHostName    RecCreationTime RecType ServiceDirection    CmtsMdIfIndex   ,,,
0   0   4199286300  Cable1/0/0  0   0   USXnet  4294746100  7710    13  0   ... 954374  aaaa.bbbb.cccc  1033134 7   ibis-instruments-1.com  1555675968867   1   2   1001    NaN
1   0   4199286300  Cable0/0/0  0   0   DSXnet  4294746100  287 14  0   ... 954374  aaaa.bbbb.cccc  96868   7   ibis-instruments-1.com  1555675968867   1   1   1001    NaN
2   0   4199290300  Cable1/0/0  0   0   USXnet  4294746100  9527731 15  0   ... 954284  dddd.bbbb.cccc  1471545334  7   ibis-instruments-1.com  1555675968867   1   2   1001    NaN
3   0   4199290300  Cable0/0/0  0   0   DSXnet  4294746100  128871002   16  0   ... 2968    dddd.bbbb.cccc  188935852314    7   ibis-instruments-1.com  1555675968867   1   1   1001    NaN
4   0   4260449700  Cable0/0/0  0   0   USXnet  4294746100  452297  17  0   ... 342739  dddd.bbbb.mmmm  77459364    7   ibis-instruments-2.com  1555675968868   1   2   1001    NaN

编辑:在 CmMacAddr 列上添加点和大写

df['CmMacAddr'] = df['CmMacAddr'].str.replace('.', '').str.upper()

df['CmMacAddr'] = df['CmMacAddr'].apply(lambda x: '.'.join(x[i:i+2] for i in range(0,len(x), 2)))

解释

第一行代码读取用“|”分隔列的 .csv (默认为逗号 (,))。
第二行我重命名了列名,因为你的 csv 没有header,我只选择了一行(df.iloc[0, :]),然后我覆盖了所有值(apply),由 '=' 拆分并从索引 0 中获取值
。最后一行代码非常类似于第二个,但我从每个拆分中获取第二个值并用这个新值替换所有行。

如果您逐行执行我的代码并df.head()在它们之间添加,您将看到演变:)


推荐阅读