0

tried so many methods to get the output

import pandas as pd

numbers= []
for i in range(100,5100,100):
    numbers.append((30,i))

df = pd.DataFrame(list(zip(*[numbers])))
df.to_csv('file.csv',header=False,index=False,index_label=None

output of this program:

file.csv:

"(30, 100)"

"(30, 200)"

"(30, 300)"

"(30, 400)"

"(30, 500)"

"(30, 600)"

"(30, 700)"

but actual output I want

file.csv:

30,100

30,200

30,300

30,400

30,500

30,600
glibdud
  • 7,550
  • 4
  • 27
  • 37
satya
  • 84
  • 8

2 Answers2

2

You need to update your function like below:

import pandas as pd

numbers= []
for i in range(100,5100,100):
    numbers.append((30,i))
# zip is not required for numbers list.
df = pd.DataFrame(numbers)
df.to_csv('file.csv',header=False,index=False,index_label=None)

You use zip if you have to map the similar index of multiple containers.

Raghav salotra
  • 820
  • 1
  • 11
  • 23
1

Just replace pd.DataFrame(zip[*numbers])' with 'pd.DataFrame(numbers)

import pandas as pd

numbers = []
for i in range(100, 5100, 100):
    numbers.append((30, i))

df = pd.DataFrame(numbers)
df.to_csv('file.csv', header=False, index=False, index_label=None)

Explanation: DataFrame(list(zip(*[numbers]))) will create a one column dataframe with row values tuples (30, 100), (30, 200), (30, 300), etc.

DataFrame(numbers) will create a two column dataframe where column 0 will have the row values 30, 30, 30, etc and column 1 the row values 100, 200, 300, etc.

Just do print(df.head(20)) to see the effect.

By the way a more Pythonic way to create numbers is with a list comprehension:

numbers = [(30, i) for i in range(100, 5100, 100)]

Bruno Vermeulen
  • 2,970
  • 2
  • 15
  • 29