我从多行文本文件中提取数据点,并try 将组数据添加到数据帧中的单行,但我在自己的行上获取每个数据点,我想将其展平为2行GROUP1和GROUP2.我对Python 还是个新手.此外,如果有一种更有效的方法来做到这一点,那也是很好的.我试了groupby()次,但这似乎不起作用?先谢谢你.

import pandas as pd

data = """
Jan 2024
Group1 02/02/2024
dog 10 20
cat 21 32
Group2 05/02/2024
dog 23 45
cat 45 65
owl 24 12
monthly
Admin 02 22
clean 05 32
"""

extract = []
dog, cat, owl = [], [], []
for line in data.splitlines():
    a = c = e = ''
    # print(line)
    if 'Group' in line:
        group = line.rsplit()[0]
    
    if 'dog' in line or 'cat' in line or 'owl' in line:
        if line.startswith("dog"):
            dog, a, b = line.split()
        elif line.startswith("cat"):
            cat, c, d = line.split()
        elif line.startswith("owl"):
            owl, e, f = line.split()
        
        extract.append({
            'group': group,
            'dog': a,
            'cat': c,
            'owl': e
        })

df = pd.DataFrame(extract)
df = df[['group', 'dog', 'cat', 'owl']]
print(df)

目前,我得到了以下信息:

    group dog cat owl
0  Group1  10
1  Group1      21
2  Group2  23
3  Group2      45
4  Group2          24

我想要的是:

   group dog cat owl
0  Group1  10 21
1  Group2  23 45  24 

推荐答案

您可以在构造数据帧之前折叠行.这可以通过以下方法来实现:保持每个组一个dict column_name->value,在新组开始时刷新它,并将其添加为紧靠前的一行.别忘了在最后加一行.

extract = []
row = None

for line in data.splitlines():
    if 'Group' in line:
        if row is not None: # we have something to add
            extract.append(row)
        group = line.rsplit()[0]
        row = {'group': group} # new group starts - refreshing our dict
    
    if 'dog' in line or 'cat' in line or 'owl' in line:
        animal, val1, val2 = line.split()
        row[animal] = val1
        
if row is not None: # a final group
    extract.append(row)

df = pd.DataFrame(extract)
df = df[['group', 'dog', 'cat', 'owl']]
print(df)

输出:

    group dog cat  owl
0  Group1  10  21  NaN
1  Group2  23  45   24

Python相关问答推荐

Select 用a和i标签包裹的复选框?

'discord.ext. commanders.cog没有属性监听器'

如何记录脚本输出

用Python解密Java加密文件

Python,Fitting into a System of Equations

为什么以这种方式调用pd.ExcelWriter会创建无效的文件格式或扩展名?

Python+线程\TrocessPoolExecutor

在含噪声的3D点网格中识别4连通点模式

Plotly Dash Creating Interactive Graph下拉列表

可以bcrypts AES—256 GCM加密损坏ZIP文件吗?

使用Python从rotowire中抓取MLB每日阵容

从旋转的DF查询非NaN值

为什么我的sundaram筛这么低效

Discord.py -

如何合并具有相同元素的 torch 矩阵的行?

如何将泛型类类型与函数返回类型结合使用?

简单 torch 模型测试:ModuleNotFoundError:没有名为';Ultralytics.yolo';

如何在Django模板中显示串行化器错误

在MongoDB文档中仅返回数组字段

将鼠标悬停在海运`pairplot`的批注/高亮显示上