Kratos Kratos - 1 year ago 122
Python Question

create panda dataframe and append values in for loop

I have a list from which I would like to iterate over and create tuples in a pandas dataframe in order to imitate sliding window of size 4. What I am trying to do is:

tuples = pd.DataFrame()
for index, row in expertsDF.iterrows():
newlst = row['name']
counter = 0
for x in newlst:
if counter < len(newlst) - 3:
tuples['A'] = x
tuples['B'] =newlst(counter+1)
tuples['C'] =newlst(counter+2)
tuples['D'] =newlst(counter+3)
counter = counter + 1

the newlst looks like this:

list (var1, var2, var3....)

and my DataFrame should be like this:

1 var1 var2 var3 var4
2 var2 var3 var4 var5
3 var3 var4 var5 var6

Is there a way to do that in python?

Answer Source

Is this close?

import pandas as pd
tuples = pd.DataFrame(columns=['A', 'B', 'C', 'D'])
newlst = "abcdefg"
i = 0
for x in newlst:
    if i < len(newlst) - 3:
        t = pd.DataFrame([[x, newlst[i + 1], newlst[i + 2], newlst[i + 3]]],
                         columns=['A', 'B', 'C', 'D'])
    tuples = tuples.append(t, ignore_index=True)
    i += 1
print tuples

This prints:

   A  B  C  D
0  a  b  c  d
1  b  c  d  e
2  c  d  e  f
3  d  e  f  g
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download