如何使用python将数据从一个CSV重新排列并映射到另一个CSV

2024-10-06 11:22:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Amazon textract从具有多个表的图像中提取了表数据,并尝试将所有提取的数据映射到输出模板CSV中

但是,在提取的输入CSV文件中有多个表,这些表一个列在另一个下面。在每个CSV中,大约有7个表格在下面一一列出

请建议如何将值从输入映射到输出

输入CSV文件:

S.No    Item        Item_code      1st     2nd    3rd    4th    Avg
1      Math_book    BK001           27      36    35     23      30
2      Phy_book     BJ008           30      40    40     30      35
3      Hin_book     NK103           50      50    30     30      40
4      Che_book     CH001           40      40    40     20      35


S.No   Item_Name    Item_code      1st     2nd    3rd    4th    Avg
1      Math_book    BK001           27      36    35     23      30
2      Phy_book     BJ008           30      40    40     30      35
3      Hin_book     NK103           50      50    30     30      40


S.No   Product        Item_code      1st     2nd    3rd    4th    Avg
1      Phy_book     BJ008           30      40    40     30      35
2      Hin_book     NK103           50      50    30     30      40
3      Che_book     CH001           40      40    40     20      35
4      Bio_book     BI005           50      30    40     60      45

预期输出:

S.No   Product        Item_code      1st     2nd    3rd    4th
1      Math_book    BK001           54      72    70     46  
2      Phy_book     BJ008           90      120  120     90 
3      Hin_book     NK103          150      150   90     90 
4      Che_book     CH001           80      80    80     60 
5      Bio_book     BI005           50      30    40     60  

我一直试图使用的代码:

df = pd.read_csv(r'input.csv')
df2 = pd.read_csv(r'output.csv')

如何按组添加所有值通过考虑(项目、项目名称、产品)列提交df2中的值

请建议


Tags: csvnophycodemathcheitemavg
1条回答
网友
1楼 · 发布于 2024-10-06 11:22:04

只需使用grouby-

df  = df[df['S.No']!='S.No'].drop('S.No',axis=1) # drop header rows
df[df.columns.values[2:]]  = df[df.columns.values[2:]].apply(lambda x: x.astype(int)) #convert data to int type
df = df.groupby(['Item','Item_code'],as_index=False).sum()
df.to_csv('out.csv',index_label='S.No', sep= '\t') # specify the name of output file here

相关问题 更多 >