Sheaves333
Sheaves333

Reputation: 43

Is there a way to calculate the slope for each successive point in two data frames, store all the values for slope and then plot it?

df = pd.read_csv('data.csv')
v = df['Gate V']
i1 = df['Drain I.1']

     Drain V   Gate V       Drain I    
0       0.01    -5.00  3.270000e-14                
1       0.01    -4.85  1.740000e-14               
2       0.01    -4.70  2.620000e-14                
3       0.01    -4.55  6.270000e-14                
...     ...     ...    ...

I have a large .csv file that looks like the above except with a lot more data. My goal thus far has been to plot Drain I versus Gate V for several different Drain V. I've accomplished this by using the v = ... and i1 = ... statements as above, and then simply plotting i1 vs v, i2 vs v, and so on.

However, now I need to calculate the slope of every Drain I vs Gate V for every point and graph that as well. My initial thought was to use a for loop to calculate the slope for every entry in the i1 (and i2, i3...) and/or v series, something like this:

for x in i1:
    slope1 = (i1[x+1] - i1[x]) / (v[x+1] - v[x])

I'd ideally then have the slope from point to point and could graph it using matplotlib. Obviously, that for loop will not work but I'm not sure how else to go about it.

Upvotes: 4

Views: 2465

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114320

The slope as you calculate it in your loop is just the ratio of the successive diffs in the two columns:

deltas = df.diff().drop(0)
slope = deltas['Drain I'] / deltas['Gate V']

The .drop(0) will remove the first row of the diffs, which will be all NaNs to preserve the original shape.

Here is a small example:

df = pd.DataFrame({'Gate V': [-5.00, -4.85, -4.70, -4.55], 'Drain V': [0.01, 0.01, 0.01, 0.01], 'Drain I': [3.270000e-14, 1.740000e-14, 2.620000e-14, 6.270000e-14]})
deltas = df.diff().drop(0)
slope = deltas['Drain I'] / deltas['Gate V']

You now have a slope Series containing

1   -1.020000e-13
2    5.866667e-14
3    2.433333e-13
dtype: float64

A basic plot can be obtained with slope.plot():

enter image description here

Upvotes: 2

Related Questions