python - 用循环中的行填充现有数据框

标签 python pandas

我试过 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

预期输出

enter image description here

如有任何帮助,我们将不胜感激。

最佳答案

你可以试试这个,

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/

相关文章:

python - 使用dpkt解析pcap文件

python-3.x - 根据来自另一个数据框python pandas的部分字符串匹配替换列值

python - genfromtxt 返回 NaN 行

python - 如何更改 Pandas 系列的索引值

python - 按键更新 pandas DataFrame

python - 计算 Pandas 时间序列上的每日事件

python - 如何将多个 seaborn 图保存到同一个 pdf/png 文件?

python - 如何使用pyspark中的reduceByKey将元素追加到列表中

python - "Time Limit Exceeded"关于 LeetCode 的三和题?

python - 使用 CouchDB-Python 批量取消删除 CouchDB 文档