我有一个空的数据框:
dfObj = pd.DataFrame(columns=['combo', 'item1', 'item2', 'group1', 'group2', 'category1', 'category2', 'title1', 'title2'])
然后我在单独的变量中有这些值:
combo = 'A | B|'
item1 = 'A'
item2 = 'B'
group1 = 'phones'
group2 = 'cases'
cat1 = 'smartphones'
cat2 = 'leather cases'
title1 = 'Samsung galaxy S9+'
title2 = 'Casey for S9+'
我想以某种方式获取数据框行,以后可以将其追加到我的数据框中。现在,我正在经历一个for循环,并使用.iloc[]
将值放到特定的位置,但是有没有更好的方法呢?。
答案 0 :(得分:2)
创建变量列表,循环分配给嵌套列表,最后一次传递给DataFrame
构造函数一次:
L = [combo, item1, item2, group1, group2, cat1, cat2, title1, title2]
cols = ['combo', 'item1', 'item2', 'group1', 'group2',
'category1', 'category2', 'title1', 'title2']
#simulate loop
out = []
for i in range(2):
out.append(L)
dfObj = pd.DataFrame(out, columns=cols)
print (dfObj)
combo item1 item2 group1 group2 category1 category2 \
0 A | B| A B phones cases smartphones leather cases
1 A | B| A B phones cases smartphones leather cases
title1 title2
0 Samsung galaxy S9+ Casey for S9+
1 Samsung galaxy S9+ Casey for S9+
另一种解决方案是创建字典:
d = {'combo': combo, 'item1': item1, 'item2': item2, 'group1': group1,
'group2': group2, 'category1': cat1, 'category2': cat2,
'title1': title1, 'title2': title2}
print (d)
out = []
for i in range(2):
out.append(d)
dfObj = pd.DataFrame(out)
print (dfObj)
category1 category2 combo group1 group2 item1 item2 \
0 smartphones leather cases A | B| phones cases A B
1 smartphones leather cases A | B| phones cases A B
title1 title2
0 Samsung galaxy S9+ Casey for S9+
1 Samsung galaxy S9+ Casey for S9+