0

I looked through the suggestions and honestly, they couldn't help me enough not to continue with posting this.

I'm trying to organize data in a csv file to a new file. I can print out the results, I just can't write them to a new file. What I have so far is something that writes, but not the desired results. (fieldnames is in there because I changed from DictWriter to just writer as per dict and str issues)

import csv
import pandas as pd

with open('TastyTrades.csv', 'r') as trade_history:
    trade_reader = pd.read_csv('TastyTrades.csv')
    df = trade_reader.loc[trade_reader['Action'].isin(['BUY_TO_OPEN', 'SELL_TO_OPEN']) & (trade_reader['Instrument Type'] == 'Equity Option')]

    with open('new_taste.csv', 'w') as open_trades:
        fieldnames = ['Date', 'Type', 'Action', 'Symbol', 'Instrument Type', 'Description', 'Value', 'Quantity',
                      'Average Price', 'Commissions', 'Fees', 'Multiplier', 'Underlying Symbol', 'Expiration Date',
                      'Strike Price', 'Call or Put']
        csv_writer = csv.writer(open_trades, delimiter='\t')

        for line in trade_reader:
            csv_writer.writerow(line)

The results I am getting brings back the header with each row making up each header name.

D   a   t   e

T   y   p   e

A   c   t   i   o   n

S   y   m   b   o   l

I   n   s   t   r   u   m   e   n   t       T   y   p   e

D   e   s   c   r   i   p   t   i   o   n

V   a   l   u   e

What I'm trying to get is the following without it being indexed. (I'm running this as a print(df) in pycharm just as a show)

                         Date   Type  ... Strike Price Call or Put
0    2020-02-14T15:49:12-0500  Trade  ...        127.0        CALL
1    2020-02-14T15:49:11-0500  Trade  ...        107.0         PUT
2    2020-02-14T15:49:11-0500  Trade  ...        128.0        CALL
3    2020-02-14T15:49:11-0500  Trade  ...        106.0         PUT
8    2020-02-14T12:19:30-0500  Trade  ...          2.5        CALL
Luck Box
  • 75
  • 1
  • 10
  • 2
    I don't mean this to be snarky: is there a reason you're not using [`.to_csv()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html)? – mechanical_meat Feb 16 '20 at 02:07
  • 1
    Yes, there's a very good reason: because I'm a noob and I easily get lost in Google learning other things that aren't the things I'm trying to learn. You're amazing and thank you! – Luck Box Feb 16 '20 at 02:35
  • Does this answer your question? [Writing a pandas DataFrame to CSV file](https://stackoverflow.com/questions/16923281/writing-a-pandas-dataframe-to-csv-file) – AMC Feb 16 '20 at 04:26

1 Answers1

0

This will work friend

df.to_csv(r'C:/your/file/path.csv')