Home > Net >  save dataframe values to txt file
save dataframe values to txt file

Time:04-27

so i wanna save this dataframe into a text file:

print(myDF)
             0         1         2         3         4
away       0.0  0.000000  0.000000  0.000000  0.051917
g          0.0  0.000000  0.051093  0.000000  0.000000
attract    0.0  0.000000  0.025547  0.000000  0.000000
might      0.0  0.000000  0.000000  0.000000  0.051917
working    0.0  0.000000  0.025547  0.000000  0.000000
...        ...       ...       ...       ...       ...
stuck      0.0  0.089413  0.000000  0.000000  0.000000
bit        0.0  0.000000  0.025547  0.000000  0.000000

To a similar way, each value separeted by space and each line separeted by '\n' (jumpline)

0.0  0.000000  0.000000  0.000000  0.051917
0.0  0.000000  0.051093  0.000000  0.000000
0.0  0.000000  0.025547  0.000000  0.000000
0.0  0.000000  0.000000  0.000000  0.051917
0.0  0.000000  0.025547  0.000000  0.000000
0.0  0.089413  0.000000  0.000000  0.000000
0.0  0.000000  0.025547  0.000000  0.000000

CodePudding user response:

You can use to_csv like this:

import pandas as pd

data = {'product_name': ['laptop', 'printer', 'tablet', 'desk', 'chair'],
        'price': [1200, 150, 300, 450, 200]
        }

df = pd.DataFrame(data)

df.to_csv(r'pandas.txt', header=None, index=None, sep=' ', mode='a')

Output:

laptop 1200
printer 150
tablet 300
desk 450
chair 200
  • Related