Home > front end >  length of list len(list) resulting wrong value in Python
length of list len(list) resulting wrong value in Python

Time:04-09

It might sound trivial but I am surprised by the output. Basically, I have am calculating y = m*x b for given a, b & x. With below code I am able to get the desired result of y which a list of 20 values. But when I am checking the length of the list, I am getting 1 in return. And the range is (0,1) which is weird as I was expecting it to be 20. Am I making any mistake here?

  a = 10
  b = 0
  x = df['x']

print(x)

 

0     0.000000
1     0.052632
2     0.105263
3     0.157895
4     0.210526
5     0.263158
6     0.315789
7     0.368421
8     0.421053
9     0.473684
10    0.526316
11    0.578947
12    0.631579
13    0.684211
14    0.736842
15    0.789474
16    0.842105
17    0.894737
18    0.947368
19    1.000000


y_new = []
for i in x:
  y = a*x  b
  y_new.append(y)
len(y_new)

Output: 1

print(y_new)

[0      0.000000
1      0.526316
2      1.052632
3      1.578947
4      2.105263
5      2.631579
6      3.157895
7      3.684211
8      4.210526
9      4.736842
10     5.263158
11     5.789474
12     6.315789
13     6.842105
14     7.368421
15     7.894737
16     8.421053
17     8.947368
18     9.473684
19    10.000000
Name: x, dtype: float64]

CodePudding user response:

I would propose two solutions:

The first solution is : you convert your columnn df['x'] into a list by doing df['x'].tolist() and you re-run your code and also you should replace ax b by ai b

The second solution is (which I would do): You convert your df['x'] into an array by doing x = np.array(df['x']). By doing this you can do some array broadcasting. So, your code will simply be :

x = np.array(df['x'])
y = a*x   b

This should give you the desired output. I hope this would be helpful

CodePudding user response:

With the code below, I have a length of 20 for the array y_new. Are you sure to print the right value? According to this post, df['x'] returns a panda Series so df['x'] is equivalent to pd.Series(...).

df['x'] — index a column named 'x'. Returns pd.Series

import pandas as pd

a = 10
b = 0
x = pd.Series(data=[0.000000,0.052632,0.105263,0.157895,0.210526, 0.263158, 0.315789, 0.368421, 0.421053,0.473684,0.526316,0.578947,0.631579
,0.684211,0.736842,0.789474,0.842105,0.894737,0.947368,1.000000])

y_new = []
for i in x:
  y = a*x  b
  y_new.append(y)
print("y_new length: "   str(len(y_new)) )

Output:

y_new length: 20
  • Related