Home > Software design >  Append won't add a Arraylike to an array
Append won't add a Arraylike to an array

Time:01-05

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

CodePudding user response:

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()

CodePudding user response:

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]
  • Related