Engine
Engine

Reputation: 5422

loop values directly to csv

to make things simple, say I have the following:

for i in range(0 ,100):
   value1 = i*0.01  
   value2 = i*2.75 

how to can I write value1 and value2 into a csv file using pandas, so that the result looks as followed:

value1        value2 
0               0
0.01            2.75
0.02            5.25
.....            ...

I've been search but could find any example that using a simple value as input to a csv file. any idea how may I do this!

Upvotes: 2

Views: 61

Answers (5)

chfw
chfw

Reputation: 4592

Here is an non-pandas solution:

>>> import pyexcel as p
>>> def data_gen(length):
...     yield ['value1', 'value2']
...     for i in range(0, length):
...         value1 = i*0.01  
...         value2 = i*2.75
...     yield [value1, value2]
>>> p.save_as(array=data_gen(100), dest_file_name='test.csv')

Dependency is pyexcel

Upvotes: 0

Stuart
Stuart

Reputation: 9858

If you don't need to use pandas, you can use the csv module:

import csv
with open('file.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['value1', 'value2'])
    for i in range(0 ,100):
        value1 = i*0.01  
        value2 = i*2.75 
        writer.writerow([value1, value2])

If you are using pandas, then there is usually a more naturally pandas-y way of constructing a dataframe than one value at a time. In this case, for example:

import pandas as pd
s = pd.Series(range(100))
df = pd.DataFrame({'value1': s * .01, 'value2': s * 2.75})
df.to_csv('output.csv', index=False)

Upvotes: 2

Chiheb Nexus
Chiheb Nexus

Reputation: 9257

Another way, using a generator:

import pandas as pd

def get_val(limit=100):
    for k in range(limit):
        yield k * 0.01, k * 2.75

pd.DataFrame(get_val(), columns=["value1", "value2"]).to_csv("output.csv", index=False)

Upvotes: 2

nacho
nacho

Reputation: 5397

You can save a pandas df to csv with:

df.to_csv(file_name)

Upvotes: 0

asongtoruin
asongtoruin

Reputation: 10359

If you're committed to using pandas, you could use a dictionary and the .from_dict() and to_csv() methods of a DataFrame:

import pandas as pd

data = {'value1': [i*0.01 for i in range(100)],
        'value2': [i*2.75 for i in range(100)]}

pd.DataFrame.from_dict(data).to_csv('output.csv', index=False)

This would save the two columns to output.csv in the format required.

EDIT: the above answer assumed value1 and value2 didn't really have any use for you, and thus could be created with a list comprehension. If you're actually using these values to do some other calculations, it may help you to use a defaultdict to update the dictionary of values while they are in use, and then output at the end, like so:

import pandas as pd
from collections import defaultdict

output_values = defaultdict(list)

for i in range(0, 100):
    value1 = i * 0.01
    value2 = i * 2.75

    output_values['value1'].append(value1)
    output_values['value2'].append(value2)

    # Do other things with these values....

pd.DataFrame.from_dict(output_values).to_csv('output.csv', index=False)

Upvotes: 3

Related Questions