Как читать и печатать строки с общими данными в CSV, используя pandas - PullRequest
0 голосов
/ 27 февраля 2020

Я использую приведенный ниже код для чтения определенных строк из CSV, используя python и pandas. Но я застрял, когда хочу напечатать общие данные, текстовые строки. Я хочу напечатать строку, содержащую код заказа, как и 00157B. PFA Скриншот сценария и прилагаемого кода, который я использую.

rows = pd.read_csv('SampData.csv', skiprows=[1,3])
print(rows.head())

Data Image

Ответы [ 2 ]

0 голосов
/ 27 февраля 2020

Вы можете попробовать один из них -

Если вы хотите выполнить сравнение по всему члену в столбце OrderCode (например, 00157B):

 filtered = rows[rows['OrderCode'] == '00157B'].reset_index(drop=True)
 filtered.to_csv('output.csv', index=False)

В Если вы хотите выполнить сравнение по неполному члену в столбце OrderCode (например, OrderCodes с < Test 1 >):

filtered = rows[rows['OrderCode'].str.contains('< Test 1 >')].reset_index(drop=True)
filtered.to_csv('output.csv', index=False)
0 голосов
/ 27 февраля 2020

Использование Pandas для этого может быть сделано, но это излишне. Я бы просто порекомендовал модуль csv, с которым довольно легко работать и который содержит множество онлайн-документации Вот игрушечный пример, который делает в значительной степени то, что вы ищете, я думаю

файл data.csv:

Order Number, Item, quantity
76XY, Cheese, 3
88TG, Broccoli, 44
76XY, Cookies, 1000
98UU, Coke, 1

Короткий файл, который манипулирует 2 файлами CSV:

import csv
input_file = 'data.csv'
output_file = 'found_orders.csv'
magic_order = '76XY'

with open(output_file, 'w') as target:
    target_writer = csv.writer(target)

    # open the source
    with open(input_file, 'r') as source:
        source_reader = csv.reader(source)
        # now both are "open and ready"
        # get the header from the first read of the source
        header = source_reader.__next__()

        # write to the modified file
        target_writer.writerow(header)

        # now use loop to loop through all rows and look for the order number
        # if found, print it to console and write it out to new csv
        # some extra print statements to see what is going on.  Recall
        # when csv reader reads a row, it reads it in as a list
        for row in source_reader:
            print('just read row: ', row)
            order = row[0]  # the position in the list of the order
            if order == magic_order:
                print('it matches the magic order')
                target_writer.writerow(row)
            else:
                print('not a match')
            print()

# if you use the 'with' command structure, it will close the files automatically
print('done')

Выход (на консоль). Выходной файл - это то, что вы ожидаете увидеть .:

just read row:  ['76XY', ' Cheese', ' 3']
it matches the magic order

just read row:  ['88TG', ' Broccoli', ' 44']
not a match

just read row:  ['76XY', ' Cookies', ' 1000']
it matches the magic order

just read row:  ['98UU', ' Coke', ' 1']
not a match

done
[Finished in 0.0s]
...