Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

Convert a pandas dataframe to tab separated list in Python

I have a dataframe like below:

import pandas as pd
data = {'Words':['actually','he','came','from','home','and','played'], 
        'Col2':['2','0','0','0','1','0','3']}
data = pd.DataFrame(data) 

The dataframe looks like this:

DataFrame looks like below

I write this dataframe into the drive using below command:

np.savetxt('/folder/file.txt', data.values,fmt='%s', delimiter='')

And the next script reads it with below line of code:

data = load_file('/folder/file.txt') 

Below is load_file function to read a text file.

def load_file(filename):
    with open(filename, 'r', encoding='utf-8') as f:
        data = f.readlines()
    return data

The data will be a tab separated list.

print(data)

gives me the following output:

['actually2
', 'he0
', 'came0
', 'from0
', 'home1
', 'and0
', 'played3
']

I dont want to write the file to drive and then read it for processing. Instead I want to convert the dataframe to a tab separated list and process directly. How can I achieve this?
I checked for existing answers, but most just convert list to dataframe and not other way around. Thanks in advance.

question from:https://stackoverflow.com/questions/65949733/convert-a-pandas-dataframe-to-tab-separated-list-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try using .to_csv()

df_list = data.to_csv(header=None, index=False, sep='').split('
')

df_list:

['actually2',
 'he0',
 'came0',
 'from0',
 'home1',
 'and0',
 'played3'
]

v = df.to_csv(header=None, index=False, sep='').rstrip().replace('
', '
\n').split('\n')

df_list:

['actually2
',
 'he0
',
 'came0
',
 'from0
',
 'home1
',
 'and0
',
 'played3
'
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...