2

I want to ignore empty columns in a dataframe.

For Example:

sample.csv

Id  Name  Address    Contact   Item   Rate Qty  Price
1   Mark  California 98429102  Shirt  57    2    8
2   Andre Michigan   92010211

I have tried:

import pandas as pd
df = pd.read_csv('sample.csv')
df = df.fillna('')

df.to_csv('sample.txt',sep='*',index=False, header=False)

The sample.txt looks like

1*Mark*California*98429102*Shirt*57*2*8
2*Andre*Michigan*92010211****

I want to remove the empty columns here. The sample.txt should look like this:

1*Mark*California*98429102*Shirt*57*2*8
2*Andre*Michigan*92010211
6
  • 1
    Why would you want to do that? Commented Feb 12, 2021 at 10:00
  • The format of the output file is like that. Commented Feb 12, 2021 at 10:01
  • 1
    That looks like a badly specified format. I don't think pandas will help you here. You'll probably have to do some post-processing on the text file directly. Commented Feb 12, 2021 at 10:02
  • At best you could split the dataframe in 2 (with a boolean mask like df['item'].isna()) and write 2 separate CSV files. Commented Feb 12, 2021 at 10:04
  • I need to specify all data in a single txt file Commented Feb 12, 2021 at 10:19

2 Answers 2

2

Just use a memory buffer and strip()

import io
df = pd.read_csv(io.StringIO("""1*Mark*California*98429102*Shirt*57*2*8
2*Andre*Michigan*92010211****"""), sep="*", header=None)

with open("sample.csv", "w") as f: 
    f.write("\n".join([l.strip("*") for l in df.to_csv(sep="*",header=None, index=None).split("\n")]))

with open("sample.csv") as f: print(f.read())

output

1*Mark*California*98429102*Shirt*57.0*2.0*8.0
2*Andre*Michigan*92010211

Sign up to request clarification or add additional context in comments.

Comments

1

What about

sep = '*'
(
    df
    .applymap(str)
    .apply(
        # Removes all empty fields
        # axis=1, func=lambda s: sep.join(el for el in s if el)
        # Removes trailing fields
        axis=1, func=lambda s: sep.join(s).strip('*')
    )
    .to_csv('sample.txt', index=False, header=False)
)

3 Comments

This removes empty elements from all the fields. I just want to remove trailing fields.
@Atom Indeed. See update. Rather minor. Any question ?
Ok @Jaroslav. As long as it derives from K&R's style (or 1TBS), I am okay with it.

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.