【问题标题】:Pandas: Replacing column values in dataframe columnsPandas:替换数据框列中的列值
【发布时间】:2018-09-29 06:35:29
【问题描述】:

我对这个问题的目标是在每个列值的每个字符之间插入一个逗号,这些值已经过哈希处理并填充到 19 位的长度。

下面的代码部分工作,但尝试将 f_comma 函数应用于列值时会弄乱数组值...感谢您的帮助!

我从其他问题中得到了一些答案,并创建了以下代码: 使用这个功能 -

def f_comma(p_string, n=1):
    p_string = str(p_string)
    return ','.join(p_string[i:i+n] for i in range(0, len(p_string), n))

并打开一个 tsv 文件

data = pd.read_csv('a1.tsv', sep = '\t',  dtype=object)

我已经修改了另一个答案以执行以下操作 -

h = 1
try:
    while data.columns[h]:
        a = data.columns[h]
        data[a] = f_comma((abs(data[a].apply(hash))).astype(str).str.zfill(19))
        h += 1
except IndexError:
    pass

返回这个数组

array([[ '0, , , , ,4,1,7,5,7,0,1,4,5,4,6,1,6,5,3,1,4,6,1,\n,N,a,m,e,:, ,d,a,t,e,,, ,d,t,y,p,e,:, ,o,b,j,e,c,t',
        '0, , , , ,6,2,9,1,6,7,0,8,4,2,8,2,9,1,0,9,5,9,4,\n,N,a,m,e,:, ,n,a,m,e,,, ,d,t,y,p,e,:, ,o,b,j,e,c,t']], dtype=object)

没有 f_comma 函数,数组看起来像 -

array([['3556968867719847281', '3691880917405293133']], dtype=object)

目标是这样的数组-

array([['3,5,5,6,9,6,8,8,6,7,7,1,9,8,4,7,2,8,1', '3,6,9,1,8,8,0,9,1,7,4,0,5,2,9,3,1,3,3']], dtype=object)

【问题讨论】:

    标签: python pandas numpy normalization


    【解决方案1】:

    您应该能够使用 pandas 字符串函数。 例如https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.join.html

    df["my_column"].str.join(',')

    【讨论】:

    • 是的,确实有效,我将行更改如下: data[a] = (abs(data[a].apply(hash))).astype(str).str.zfill( 19) 并添加 data[a] = data[a].str.join(',') 结果!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    相关资源
    最近更新 更多