我有一个列表,我想迭代并在pandas数据框中创建元组,以模仿大小为4的滑动窗口。我想要做的是:
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
newlst看起来像这样:
list (var1, var2, var3....)
我的DataFrame应该是这样的:
A B C D
1 var1 var2 var3 var4
2 var2 var3 var4 var5
3 var3 var4 var5 var6
有没有办法在python中做到这一点?
答案 0 :(得分:1)
这是否接近?
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
打印:
A B C D
0 a b c d
1 b c d e
2 c d e f
3 d e f g
答案 1 :(得分:1)
如何从Series对象创建DataFrame?
import pandas as pd
data_list = list(map(lambda x: 'var{}'.format(x),range(0,100)))
df = pd.Series(data_list[0:97]).to_frame(name='A')
df['B'] = pd.Series(data_list[1:98])
df['C'] = pd.Series(data_list[2:99])
df['D'] = pd.Series(data_list[3:100])
df.head()
# output
# A B C D
# 0 var0 var1 var2 var3
# 1 var1 var2 var3 var4
# 2 var2 var3 var4 var5
# 3 var3 var4 var5 var6
# 4 var4 var5 var6 var7