2

I'm trying to convert some data to pandas dataframe. Somehow, the dataframe turned out to be empty. The print statement shows the following (part of it)

Empty DataFrame
Columns: []
Index: [count  "a" "33" "37" "asd7"]
Empty DataFrame
Columns: []
Index: [data  "2434" "33" "37" "[email protected]"]

I'd like to write the dataframe to a csv file. Since the dataframe is empty, can I write the indexes into a csv file like

count,data
a,2434
33,33
37,37
asd7,[email protected]

I know I can write a dataframe to csv using data.to_csv, but how do I achieve the above stated?

2 Answers 2

2
df1 = pd.DataFrame(index=["a", "33", "37", "asd7"], )
df2 = pd.DataFrame(index=["2434", "33", "37", "[email protected]"])
df1.index.name = 'count'
df2.index.name = 'data'

You already have objects similar to df1 and df2. Just do:

df1.reset_index(inplace=True)
df2.reset_index(inplace=True)

df3 = pd.concat([df1, df2], axis=1)

gives

   count data
0   a    2434
1   33   33
2   37   37
3   asd7 [email protected]

finally:

df3.to_csv("file_name.csv")
Sign up to request clarification or add additional context in comments.

1 Comment

Not related to the question, but thanks for the df1.index.name = 'count'. Did not know you could name the index.
1

Probably not the best approach but this normal for/loop with zip can write the csv as you asked:

df
Empty DataFrame
Columns: []
Index: [count, a, 33, 37, asd7]

df1
Empty DataFrame
Columns: []
Index: [data, 2434, 33, 37, [email protected]]

with open('combined_pd.csv', 'w') as f:
    for x,y in zip(df.index, df1.index):
        f.write(x + ',' + y +'\n')

>>>cat combined_pd.csv
count,data
a,2434
33,33
37,37
asd7,[email protected]

2 Comments

Looping with dataframes will likely be very slow and is more difficult to read.
@cd98, looping with dataframes of course will be slow. However, looping their indexes which are basically lists and write to file, will be much more efficient and quicker than reset_index and concat in OP use case. That said, I do like your approach to do things in pandas way :0

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.