0

I have a list with string items in it. The list is given below:

mylines = ['Status Name               DisplayName', 'Running MSSQL$DEV          SQL Server (DEV)', 'Running MSSQL$TEST         SQL Server (TEST)', 'Running MSSQLLaunchpad$DEV SQL Server Launchpad (DEV)', 'Running SQLAgent$DEV       SQL Server Agent (DEV)', 'Running SQLAgent$TEST      SQL Server Agent (TEST)', 'Running SQLBrowser         SQL Server Browser', 'Running SQLTELEMETRY$DEV   SQL Server CEIP service (DEV)', 'Running SQLTELEMETRY$TEST  SQL Server CEIP service (TEST)', 'Running SQLWriter          SQL Server VSS Writer']

I want to insert this list into a csv file in such a way that Status Name and DisplayName becomes the column headers and the whole format becomes as below:

enter image description here

I used the following code:

Import pandas as pd
df = pd.DataFrame(mylist)
df.head()

and the following comes up:

enter image description here

which is incorrect as it is only creating a single column instead of the two separate Status Name and DisplayName Column. How can I properly create the dataframe?

2 Answers 2

1

You can try to split the item in list with multiple spaces. And export that dataframe to csv without header and index so that the first row is as like header.

import pandas as pd

df = pd.DataFrame([filter(len, item.split('  ')) for item in mylist])

df.to_csv('your_csv', header=None, index=False)

If all your DisplayName has heading SQL Server, you can do

df = pd.DataFrame([item.split('SQL Server') for item in mylist[1:]], columns=['Status Name', 'DisplayName'])
df['DisplayName'] = 'SQL Server' + df['DisplayName']

# Remove heading and tailing spaces in column `Status Name`
df['Status Name'] = df['Status Name'].str.strip()
Sign up to request clarification or add additional context in comments.

2 Comments

Split should be on Tab character. Running MSSQLLaunchpad$DEV SQL Server Launchpad (DEV)
@mangupt The string in OP's list doesn't contains tab character.
0

Try with:

df[['A', 'B']] = df['AB'].str.split('    ', 1, expand=True)

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.