user15093306
user15093306

Reputation: 25

How do I create a .txt file from a pandas dataframe?

I have a dataframe in my jupyter notebook, which follows the below format for ~1500 rows:

BUSINESS    CUSTOMER_ID     RISK_RATING
PVB          1000033280         HR
SLA          1000064680         LR

I want to output this df as a .txt file, similar to how I have used df.to_csv.

I have tried this code:

np.savetxt(r'Y:\FILEPATH\df.txt', df.values, fmt='%d', delimiter='\t')

But I am currently getting this error message:

TypeError: Mismatch between array dtype ('object') and format specifier ('%d %d %d %d %d %d %d %d')

I also want to make sure the column headers ("BUSINESS", "CUSTOMER_ID" & "RISK_RATING") are included in the .txt file.

Any help would be much appreciated thank you.

Upvotes: 1

Views: 965

Answers (1)

IoaTzimas
IoaTzimas

Reputation: 10624

You can use df.to_csv and just give a .txt name to your file. See below:

df.to_csv('filename.txt')

Upvotes: 2

Related Questions