0

I have a dataframe with a column containing a list of strings 'A:B'. I'd like to modify this so there is a new column which contains a set split by ':' containing the first element.

data = [
    {'Name': 'A', 'Servers':['A:s1', 'B:s2', 'C:s3', 'C:s2']},
    {'Name': 'B', 'Servers':['B:s1', 'C:s2', 'B:s3', 'A:s2']},
    {'Name': 'C', 'Servers':['G:s1', 'X:s2', 'Y:s3']} 
]

df = pd.DataFrame(data)
df

df['Clusters'] = [
    {'A', 'B', 'C'},
    {'B', 'C', 'A'},
    {'G', 'X', 'Y'}
]
3
  • What do you want the results to look like? What have you tried? Commented Jul 4, 2019 at 20:56
  • this is a good start. Commented Jul 4, 2019 at 20:58
  • it should be the same dataframe with the column 'Clusters' added. 'Clusters' contains a set of the first element from 'Servers' split at ':'. Commented Jul 4, 2019 at 21:02

1 Answer 1

1

Learn how to use apply

  In [5]: df['Clusters'] = df['Servers'].apply(lambda x: {p.split(':')[0] for p in x})                                                                                  

  In [6]: df                                                                                                                                                         
  Out[6]: 
    Name                   Servers   Clusters
  0    A  [A:s1, B:s2, C:s3, C:s2]  {A, B, C}
  1    B  [B:s1, C:s2, B:s3, A:s2]  {C, B, A}
  2    C        [G:s1, X:s2, Y:s3]  {X, Y, G}
Sign up to request clarification or add additional context in comments.

Comments

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.