简体   繁体   中英

Pandas: Replacing column values in dataframe columns

my goal for this question is to insert a comma between every character in every column value, which have been hashed and padded to a length of 19 digits.

The code below works partially, but the array values get messed up by trying to apply the f_comma function to the column value...thanks for any help!

I've taken some of the answers from other questions and have created the following code: using this function -

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))

And opening a tsv file

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

I have modified another answer to do the following -

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

which returns this array

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)

without the f_comma function the array looks like -

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

The goal is an array like this -

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)

You should be able to use pandas string functions. eg https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.join.html

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM