0

We can assign an empty dataframe with pandas.

import pandas as pd
zero = pd.DataFrame()
zero
Empty DataFrame
Columns: []
Index: []

The zero dataframe is empty containing nothing in it,create a empty data file containing nothing in it.

fh = open('/tmp/test.txt','w')
fh.close()

The file /tmp/test.txt is empty.

newzero = pd.read_csv('/tmp/test.txt',header=None)
pandas.errors.EmptyDataError: No columns to parse from file

How to make pandas read an empty file and assign it as a empty dataframe such as zero shows ? Is there a way to add some argument to make the below commands running without error info.

newzero = pd.read_csv('/tmp/test.txt',header=None,add some argument)
newzero
Empty DataFrame
Columns: []
Index: []

2 Answers 2

1

This seems to be the straightforward way of doing it :

import pandas as pd
fh = open('/tmp/test.txt','w')
fh.close()

try:
    newzero = pd.read_csv('/tmp/test.txt',header=None)
except pd.errors.EmptyDataError:
    new_zero = pd.DataFrame()
Sign up to request clarification or add additional context in comments.

Comments

0

You can catch exception and create a empty data frame

import pandas as pd
zero = pd.DataFrame()
fh = open('/tmp/test.txt','r')
fh.close()
try:
    newzero = pd.read_csv('test.txt',header=None)
except pd.errors.EmptyDataError:
    newzero = pd.DataFrame()
        

3 Comments

Please format your code with just four blank at the beginning of the indent line.
Right. I did :)
Maybe it is better to set the two variables nozero and newzero as one newzero.

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.