0

I'm trying to make 2 files in Python. One named "1.csv" with number 1 and one named "2.csv" with number 2, but I have some problems. Any help?

import pandas as pd

HM = ['1', '2']
for h in HM:
    df = pd.DataFrame({'number':h})
    df.to_csv(h + '.csv', index=False)
1
  • What is your problem? Which error is thrown? What is the expected behaviour? What is the actual behaviour? Please refer to How do I ask a good question Commented Sep 10, 2020 at 14:42

2 Answers 2

1

You can not pass scalar values for the columns. You can either use a list:

import pandas as pd

HM = ['1', '2']
for h in HM:
    df = pd.DataFrame({'number':[h]})
    df.to_csv(h + '.csv', index=False)

or use scalar values and pass an index:

import pandas as pd

HM = ['1', '2']
for h in HM:
    df = pd.DataFrame({'number':h},index=[0])
    df.to_csv(h + '.csv', index=False)
Sign up to request clarification or add additional context in comments.

Comments

1

To create a dataframe, you can use the sample code below to fit your own needs.

#Import pandaa 
import pandas as pd 
  
# Create a list
data = [['Basketball', 'Monday'], ['Baseball', 'Saturday'], ['Football', 'Sunday']] 
  
# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['Sport', 'Day']) 
  
# print dataframe. 
df 

#Write the dataframe to a csv
df.to_csv('path/for/output.csv', sep='\t')

EDIT

For your specific problem, you can do the following to create two separate csv files.

import pandas as pd

HM = ['1', '2']
for h in HM:
    df = pd.DataFrame({'number':[h]})
    df.to_csv(h + '.csv', index=False)

Comments

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.