Save results to csv file with Python
Use csv.writer
:
import csv
with open('thefile.csv', 'rb') as f:
data = list(csv.reader(f))
import collections
counter = collections.defaultdict(int)
for row in data:
counter[row[0]] += 1
writer = csv.writer(open("/path/to/my/csv/file", 'w'))
for row in data:
if counter[row[0]] >= 4:
writer.writerow(row)
saving results in csv file
df1 = pd.read_csv('aaa.csv')
df2 = pd.read_csv('bbb.csv', header=None)
keepRow = df2[0].values
# Get rows that have on of the keepRow values in column 0
df3 = df1.loc[df1["firstColumn"].isin(keepRow)]
# drop the keepRow column
df3= df3.drop("firstColumn", axis=1)
#write to csv
df3.to_csv("ok.csv", index=False)
How to output my main() function as a CSV file
Return df
from your main
function, instead of print(df)
.
You can also use to_csv function on dataframes.
def main()
...
return df
if __name__ == '__main__':
df = main()
df.to_csv(f'{today}HPD.csv', index=False)
Exporting Python Output into CSV or Text File (Beginner)
You can use the python csv
module.
Example:
import csv
import random
data = [random.randint(1, 10) for _ in range(10)]
with open('data.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(data)
data.csv
9,3,7,4,1,3,7,8,1,3
Related Topics
Pandas Groupby Without Turning Grouped by Column into Index
Pandas Filling Missing Dates and Values Within Group
Convert Structured Array to Regular Numpy Array
How to Find Out Whether a File Is at Its 'Eof'
How to Change Sprite Colours in Pygame
How to Escape Latex Code Received Through User Input
Python Mixed Integer Linear Programming
How to Get Rid of Beautifulsoup User Warning
Pandas Select Rows and Columns Based on Boolean Condition
How to Use a Custom Comparison Function in Python 3
Why Use Os.Path.Join Over String Concatenation
How to Find First Non-Zero Value in Every Column of a Numpy Array
Why Might Python's 'From' Form of an Import Statement Bind a Module Name
How to Sort a List by Length of String Followed by Alphabetical Order