简体   繁体   中英

How can I eliminate comma at end of lines in CSV for Pandas Dataframe when only some have them?

I am trying to convert a csv file to pandas df. The data is of the following type (SROIE dataset) (this is just a small part of total file):

76,50,323,50,323,84,76,84,TAN WOON YANN
110,165,315,165,315,188,110,188,INDAH GIFT & HOME DECO
126,191,297,191,297,214,126,214,27,JALAN DEDAP 13,
129,218,287,218,287,236,129,236,TAMAN JOHOR JAYA,
100,243,324,243,324,261,100,261,81100 JOHOR BAHRU,JOHOR.
70,268,201,268,201,285,70,285,TEL:07-3507405

THE ISSUE LIES ONLY IN THE LAST COLUMN, WHICH DOESN'T DISPLAY THE ENTIRE TEXT INFORMATION I NEED. Based on an answer I found on pandas dataframe read csv with rows that have/not have comma at the end , I used the following code:

pd.read_csv(r'D:\E_Drive\everything else\C2\SROIE2019\0325updated.task1train(626p)\X00016469619.txt',usecols=np.arange(0,9), header=None)

This gave the following output: 我得到的熊猫数据框结果

The problem is that, for example in line 3 (row labelled 2 in pd dataframe)ie

126,191,297,191,297,214,126,214,27,JALAN DEDAP 13,

I need

27,JALAN DEDAP 13,

but I am getting

27

only. Same is the issue in line 5 (row labelled 4 in pd dataframe):

100,243,324,243,324,261,100,261,81100 JOHOR BAHRU,JOHOR.

I need

81100 JOHOR BAHRU,JOHOR.

but I am getting

81100 JOHOR BAHRU

The following approach might be sufficient? It first reads the rows using a standard CSV reader and rejoins the end columns before loading it into pandas.

import pandas as pd
import csv

with open('X00016469619.txt', newline='') as f_input:
    csv_input = csv.reader(f_input)
    data = [row[:8] + [', '.join(row[8:])] for row in csv_input]
        
df = pd.DataFrame(data)
print(df)

Giving you:

     0    1    2    3    4    5    6    7                          8
0   76   50  323   50  323   84   76   84              TAN WOON YANN
1  110  165  315  165  315  188  110  188     INDAH GIFT & HOME DECO
2  126  191  297  191  297  214  126  214       27, JALAN DEDAP 13, 
3  129  218  287  218  287  236  129  236         TAMAN JOHOR JAYA, 
4  100  243  324  243  324  261  100  261  81100 JOHOR BAHRU, JOHOR.
5   70  268  201  268  201  285   70  285             TEL:07-3507405

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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