Reputation: 27
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:
I used the following code:
Import pandas as pd
df = pd.DataFrame(mylist)
df.head()
and the following comes up:
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?
Upvotes: 0
Views: 44
Reputation: 30050
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()
Upvotes: 1