如何使用python在每个重复的csv行中添加不同的列数据?

2024-09-30 12:15:12 发布

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

我有以下场景:我有一个train.csv文件,如下所示。每行被提及4次,索引值相同

Index sentence ending0 ending1 ending2 ending3 

0        ABC     DEF     GHI     JKL     MNO     
0        ABC     DEF     GHI     JKL     MNO       
0        ABC     DEF     GHI     JKL     MNO     
0        ABC     DEF     GHI     JKL     MNO       
1        LKJ     KJS     AJA     QHW     IUH             
...      ...     ...     ...     ...     ...
...
...  
2 
...
...
...     

我想要得到的如下所示:

Index sentence ending-id ending 
0       ABC       0        DEF    
0       ABC       1        GHI    
0       ABC       2        JKL    
0       ABC       3        MNO    
1       LKJ       0        KJS 
...     ...      ...       ...
...
...   

Tags: 文件csvindexdefending场景trainjkl
3条回答

您可以尝试以下方法:

from itertools import cycle
df=df.set_index('Index').drop_duplicates()
newdf= pd.DataFrame(data=df.sentence, columns=['sentence'], index=df.index)
newdf['ending']=df[df.columns[1:]].values.tolist()
newdf=newdf.explode('ending')
ids = cycle([0,1,2,3])
newdf.insert(1, 'endingid', [next(ids) for idx in range(len(newdf))])
print(newdf)

输出:

      sentence  endingid ending
Index                          
0          ABC         0    DEF
0          ABC         1    GHI
0          ABC         2    JKL
0          ABC         3    MNO
1          LKJ         0    KJS
1          LKJ         1    AJA
1          LKJ         2    QHW
1          LKJ         3    IUH
df = _df.copy()
df = pd.melt(df.drop_duplicates(), id_vars=['sentence', 'Index'], value_vars=['ending0','ending1','ending2','ending3'])
df['ending-id'] = df.variable.str.extract('([0-9]+)')
df.rename(columns={'value':'ending'}, inplace=True)
df.drop('variable', axis=1, inplace=True)
df.set_index('Index', inplace=True)

到目前为止,我用这段代码得到了以下结果

sentence Index value ending
ABC        0    DEF    0
ABC        0    DEF    0
ABC        0    DEF    0

我希望得到如下结果:

Index sentence ending-id ending 
0       ABC       0        DEF    
0       ABC       1        GHI    
0       ABC       2        JKL    
0       ABC       3        MNO  

相关问题 更多 >

    热门问题