Home > Mobile >  Creating array of numbers and passing them as pandas column
Creating array of numbers and passing them as pandas column

Time:03-08

I want to create a pandas dataframe with below code

import pandas as pd
pd.DataFrame({'A' : 'First', 'B' : for i in range(1:10) : 'data'   i.astype(str)})

with this I am getting below error

File "<stdin>", line 1
    pd.DataFrame({'A' : 'First', 'B' : for i in range(1:10) : 'data'   i.astype(str)})
                                       ^
SyntaxError: invalid syntax

Could you please help me to understand where I was wrong in above code? I was trying to create below fataframe

enter image description here

Any pointer will be very appreciated.

CodePudding user response:

My answer is simple use list comprehension.

t = pd.DataFrame({'A' : 'First', 'B' : ['data' str(i) for i in range(1,11)]})

print(t)

     A       B
0  First   data1
1  First   data2
2  First   data3
3  First   data4
4  First   data5
5  First   data6
6  First   data7
7  First   data8
8  First   data9
9  First  data10

The problem with your code is that you tried to apply basic for loop in the form of list comprehension which so to resolve this you have to use proper list comprehension mentioned. Hope you got the answer that what you were doing wrong. enjoy!

CodePudding user response:

Try:

pd.DataFrame({'A' : 'First', 'B' : [f'data{i}' for i in range(1,11)]})

Output:

       A       B
0  First   data1
1  First   data2
2  First   data3
3  First   data4
4  First   data5
5  First   data6
6  First   data7
7  First   data8
8  First   data9
9  First  data10

Use, list comprehension with f-string formatting.

CodePudding user response:

Replace the for loop with a list comprehension

import pandas as pd

df = pd.DataFrame({'A' : 'First', 'B' : [f'data{i}' for i in range(1,11)]})

print(df)
       A      B
0  First  data1
1  First  data2
2  First  data3
3  First  data4
4  First  data5
5  First  data6
6  First  data7
7  First  data8
8  First  data9
9  First  data10

CodePudding user response:

Based on your example, you can do the following using an f-string instead. Also, keep in mind that the second parameter in range would be your desired value plus 1.

The syntax error arises from the list comprehension format you're trying to achieve, as well as using a ":" instead of a "," in the range function.

import pandas as pd
pd.DataFrame({'A' : 'First', 'B' : [f"data{i}" for i in range(1,11)]})
  • Related