我试过 How to build and fill pandas dataframe from for loop?但似乎无法将我的值(value)观写入我的专栏。
最终我从网页获取数据并想将其放入数据框中。
我的 header 预定义为:
d1 = pd.DataFrame(columns=['col1', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7', 'col8', 'col9',
'col10', 'col11', 'col12', 'col13', 'col14', 'col15', 'col16', 'col17'])
现在我有了在 for 循环中获得的值,我如何将这些行写入每一列,然后重复回到第 1 到 17 列,然后重复下一行?
row = soup.find_all('td', attrs = {'class': 'Table__TD'})
for data in row:
print(data.get_text())
示例输出行 1
Mon 11/11
SA
100
31
3-5
60.0
1-3
33.3
1-2
50.0
10
4
0
1
1
2
8
示例输出行 2
Wed 11/13
@CHA
W119-117
32
1-5
20.0
1-5
20.0
0-0
0.0
3
1
0
1
3
3
3
预期输出
如有任何帮助,我们将不胜感激。
最佳答案
你可以试试这个,
import pandas as pd
columns = [
'col1',
'col2',
'col3',
'col4',
'col5',
'col6',
'col7',
'col8',
'col9',
'col10',
'col11',
'col12',
'col13',
'col14',
'col15',
'col16',
'col17',
]
# create dataframe
d1 = pd.DataFrame(columns=columns)
full = []
for data in soup.find_all('td', attrs={'class': 'Table__TD'}):
full.append(data.get_text())
# seperate full list into sub-lists with 17 elements
rows = [full[i: i+17] for i in range(0, len(full), 17)]
# append list of lists structure to dataframe
d1 = d1.append(pd.DataFrame(rows, columns=d1.columns))
关于python - 用循环中的行填充现有数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58830088/