Python Forum

Full Version: change for loop into numpy functions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I am having problems changing the following code including a for loop (it is running 1,5 hours by now with no solution yet) into a numpy function. Can someone help me? I could not solve it.
The issue is, that I have double Nodes with different values for tension and I need to average the tension for each node, to have an array or DataFrame just including each Node once.

'Node' values are some integers.
'Spannung' values are floats (tension values belonging to Nodes, which I want to average for same Nodes)

# next two lines are not the problem, just to understand my script maybe
df = pd.DataFrame({'Node': array[:, 0], 'Spannung': array[:, 1]})
df = df.sort_values(by=['Node'])

# last node (integer)
last_node = df["Node"].iloc[-1]

# creating empty DataFrame
df2 = pd.DataFrame({'Node':[], 'Spannung':[]})

# iterating over each Node in order to fill df2 with each node and its averaged tansion value
for i in range(1, last_node):
    meanvalue = df[df['Node'] == i].mean()
    df2.append(pd.DataFrame({'Node':[i], 'Spannung':[meanvalue.at['Spannung']]}))
I would be so happy if someone could help me!
Thank you very much,
ToffiFaye
It's look like results coming from FEM Smile

My comments:
  • "append" is your enemy (dynamic allocation memory = time consuming)
  • "numpy.unique" provides you a new matrix without double node values ⇒ then "numpy.size" gives you the number of rows of your new matrix ⇒ use "numpy.zeros" to reserve in memory the matrix (gain of time)
  • sorting nodes numbers is a good idea: the second node follows immediatly the first one ⇒ you would be able to sum "i" index with "i+1" one (so I think vectorization use is possible)

I do not use Pandas, but frames seem to be no more no less that disctionnaries (Keys + values), so it is easy to extract it and to work with, isn't it?