简体   繁体   English

在单独的数据框中收集 ID

[英]Collecting ids in separate dataframe

I am stuck in a situation after grouping my data through ids.通过 id 对我的数据进行分组后,我陷入了困境。 Now I want to collect them with full info with the same ids.现在我想用相同的 id 收集它们的完整信息。

Current => I got this result after using group by id's.当前 => 在使用 group by id 后我得到了这个结果。 Expected=>every same id with all info as shown in the pic预期 => 具有所有信息的每个相同 id,如图所示

输出应该像

dfs=pd.read_excel('tns1.xlsx')
grp = dfs.groupby('entity_id')
da  = grp.groups
for entity_id,show in grp:
  print(show)
  print(da)

Now I have expected output also but the problem is I am getting in extracting them correctly & then to write in excel using the below loop I am trying to extract but I do not think so that it is extracting properly besides it is running thousand of times as many rows are there现在我也有预期的输出,但问题是我正在正确地提取它们然后使用下面的循环在 excel 中写入我正在尝试提取但我不认为它除了运行数千次之外还可以正确提取因为有很多行

So you can collect the individual data to list and then write it to csv.因此,您可以收集要列出的个人数据,然后将其写入 csv。

Data setup for illustration:用于说明的数据设置

import pandas as pd
from io import StringIO
raw_data="""
entity_id,Name,Status,Date
2244,Abhi,Active,10-06-2021
2244,Abhi2,Blocked,10-06-2021
6666,other1,Blocked,10-06-2021
6666,other,Active,10-06-2021
"""
dfs=pd.read_csv(StringIO(raw_data))

append all the dfs in a list:将所有 dfs 附加到列表中:

grp = dfs.groupby('entity_id')
da  = grp.groups
groups_as_list=[]

for entity_id,show in grp:
    groups_as_list.append(show)# append all dfs in a list

then write the list of dataframes to csv.然后将数据帧列表写入 csv。

with open("my_results.csv","w") as f:# open file for write
    for each_df in groups_as_list:
            each_df.to_csv(f,index=False)
            f.write("\n") # write empty line to csv

so the result will look like the following:( you can tweak it further based on need)所以结果将如下所示:(您可以根据需要进一步调整) 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM