2

I have thousands of hostname, those i want to be assigned into different columns based on their first initial three letters. I see this can be done if its small list ans i know the initial letters but i have huge list.

I have google a lot but did not get any proper hint, tried df.assign but that's something not great fit.

Example hostname:

fox001
fox002
fox003
fox004
fox005
fox006
dbx001
dbx002
dbx003
dbx004
dbx005
dbx006
trd001
trd002
trd003
trd004
trd005
trd006
spl001
spl002
spl003
spl004
spl005
spl006

What is expected:

fox_host   db_host  trd_host spl_host (<-- column names)
fox001     dbx001   trd001   spl001
fox002     dbx002   trd002   spl002
fox003     dbx003   trd003   spl003
fox004     dbx004   trd004   spl004
fox005     dbx005   trd005   spl005
fox006     dbx006   trd006   spl006

my dataframe:

df = pd.read_csv('inventory_hostanme',header=None).rename( columns={ 0:"hostnames"})
print(df)

hostnames
fox001
fox002
fox003
fox004
fox005
fox006
dbx001
dbx002
dbx003
dbx004
dbx005
dbx006
trd001
trd002
trd003
trd004
trd005
trd006
spl001
spl002
spl003
spl004
spl005
spl006

2 Answers 2

2

Use Series.groupby to group the column hostnames on the first three letters of the host value, then use pd.concat along axis=1 to concat each of the grouped dataframe creating a new dataframe with separate columns for each hosts:

hosts = pd.concat([
    g.rename(f'{k}_host').reset_index(drop=True)
    for k, g in df['hostnames'].groupby(df['hostnames'].str[:3])], axis=1)

Result:

# print(hosts)

  dbx_host fox_host spl_host trd_host
0   dbx001   fox001   spl001   trd001
1   dbx002   fox002   spl002   trd002
2   dbx003   fox003   spl003   trd003
3   dbx004   fox004   spl004   trd004
4   dbx005   fox005   spl005   trd005
5   dbx006   fox006   spl006   trd006
6
  • 1
    Thanks @Shubham for the help +1, i will check this with my current list and getback on the results.
    – user2023
    Jul 16, 2020 at 10:59
  • @.Shubham, can you please explain g.rename(f'{k}_host') and for k, g in df['hostnames'] this will make me understand the login behind the scene as i am in learning phase.
    – user2023
    Jul 16, 2020 at 15:41
  • 1
    As far for k, g in df['hostnames'] is concerned we are iterating over each grouped series, where k refers to group key i.e the first three letters of hostname` and g refers to the grouped series itself, so for every iteration we are renaming the grouped series to desired format using g.rename(). So for example for the grouped series with k=dbx we rename it as dbx_host Jul 16, 2020 at 15:46
  • 1
    thank you. .. is there any good link to practice about these loops 🙏 🙌, i will seek your mentor-ship.
    – user2023
    Jul 16, 2020 at 15:50
  • 1
    And there is always StackOverflow where you can find interesting questions and answers. Jul 16, 2020 at 15:54
2

cumcount with .groupby of the first 3 characters in your column returns 0,1,2,3,4 for each group of letters. From there, pivot the dataframe and change the column headers:

df['a'] = df['hostnames'].str[0:3]
df['index'] = df.groupby(['a'])['a'].transform('cumcount')
df = df.pivot(values='hostnames', columns='index').apply(lambda x: pd.Series(x.dropna().values))
df.columns = df.iloc[0].str[0:3] + '_host'

output:

    dbx_host fox_host  spl_host     trd_host
0   dbx001   fox001    spl001       trd001
1   dbx002   fox002    spl002       trd002
2   dbx003   fox003    spl003       trd003
3   dbx004   fox004    spl004       trd004
4   dbx005   fox005    spl005       trd005
5   dbx006   fox006    spl006       trd006
5
  • Thank you for the answer @David, i think df['fox001'].str[0:3] you mean df['hostnames'].str[0:3], +1 , though i will check this.
    – user2023
    Jul 16, 2020 at 11:10
  • 1
    yes, sorry, I read the first row as header when copy and pasting your dataframe. I have updated. Jul 16, 2020 at 11:12
  • @kulfi , apologies - there was a typo. It is fixed. Jul 16, 2020 at 16:51
  • Thanks so much David, would mind explaining about last two line in the post that will help me to understand.
    – user2023
    Jul 17, 2020 at 4:53
  • 1
    df = df.pivot(values='hostnames', columns='index') transforms the dataframe into the output that you want; however, it includes lots of NaN cells, which you need to use .apply(lambda x: pd.Series(x.dropna().values)) to clean up. df.columns = df.iloc[0].str[0:3] + '_host' takes the first row with .iloc[0] and the first 3 characters of each cell with .str[0:3] in that first row and adds _host to the end of each string and sets those values as the column headers with df.columns. Jul 17, 2020 at 4:57

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.