1

I have a huge list of Users_id that I want to concatenate. I know how to do it in excel but the file is much too large.

Users ID    
101 101
102 101,102
103 101,102,103
104 101,102,103,104

Here is what I want to achieve. Here is what I have so far.

import pandas as pd

df = pd.read_csv('file.csv')

pd.concat = df['USER ID']=.astype(str)+','+df['USER ID']
1
  • 1
    What is your desired output? Commented Dec 18, 2018 at 22:09

2 Answers 2

1

This is an unusual operation since your input is numeric, while your output is a sequence of comma-separated strings. One solution is to use itertools.accumulate with f-strings (Python 3.6; PEP498):

import pandas as pd
from itertools import accumulate

df = pd.DataFrame({'Users': [101, 102, 103, 104]})

def joiner(x, y):
    return f'{x},{y}'

df['Cumulative'] = list(accumulate(df['Users'].astype(str), func=joiner))

print(df)

   Users       Cumulative
0    101              101
1    102          101,102
2    103      101,102,103
3    104  101,102,103,104
Sign up to request clarification or add additional context in comments.

Comments

0

I don't understand your code. If you want to concatenate all the user ids, you should iterate over the ID column and concatenate manually all the id. The following code should do so

id_column=df['ID']
all_ids=''
for id in id_column:
    all_ids+=str(id)+','

All the IDs should be contained in variable all_ids.

1 Comment

If this is what OP wants, then ','.join(df['ID'].astype(str)) is sufficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.