abn
abn

Reputation: 1373

Dataframe index (only) to CSV python

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?

Upvotes: 2

Views: 2471

Answers (2)

cd98
cd98

Reputation: 3532

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")

Upvotes: 2

Anzel
Anzel

Reputation: 20553

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]

Upvotes: 1

Related Questions