-2

I am currently doing a project, and need to use CSV files to display information That part is figured out, but it won't allow me to append it with a known array

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import os
import glob

path = "/Users/kagemanden/Downloads/CSV Datapunkter"
csv_files = glob.glob(path + "/*.csv")
x = np.array([])

for i in csv_files:
    print(i)
    df = pd.read_csv(os.path.join(path, i))
    g=np.array([len(df)])
    print(g)
    np.append(x,g)
print(x)
plt.bar(np.arange(len(x))+1,x)
plt.show()

It is the append function that doesn't work, the rest works just fine

Basically all i know, but the Append function is an integral funcction, and i don't know how to build the code without it

  • When you try to use a numpy function (even if it is "integral"?), take time to actually read and understand its documentation - especially if your first try doesn't work. – hpaulj Jan 04 '23 at 16:45

2 Answers2

0

np.append returns a copy of the array, but do not modify the array itself. So np.append(x,g) does what you want, but you never save the result of this operation.

What you want to do is x = np.append(x, g). This way, the result of np.append is stored in x.

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import os
import glob

path = "/Users/kagemanden/Downloads/CSV Datapunkter"
csv_files = glob.glob(path + "/*.csv")
x = np.array([])

for i in csv_files:
    print(i)
    df = pd.read_csv(os.path.join(path, i))
    g=np.array([len(df)])
    print(g)
    x = np.append(x,g)
print(x)
plt.bar(np.arange(len(x))+1,x)
plt.show()
Roman
  • 16
  • 1
0

Don't try to imitate a list method with arrays. np.append is NOT a list append clone! Even when it works it is slower.

x = []
for i in csv_files:
    print(i)
    df = pd.read_csv(os.path.join(path, i))
    x.append(len(df))

or simply

x = [len(pd.read_csv(os.path.join(path,i)) for i in csv_files]
hpaulj
  • 221,503
  • 14
  • 230
  • 353