I am working on a data analysis project. The file Data_Count.csv has two columns and was created using the pandas value_counts() function. One of the columns has a heading while the other does not. How can I make it so both columns have the headings "Distance" and "Frequency" respectively without having to create a new file? Here is my code so far. Sorry, I am new to python so my code isn't that efficient.
if __name__ == "__main__":
count = int(input("How many distance entries do you wish to record?: "))
with open('results.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
writer.writerows(calculate(count))
df = pd.read_csv("results.csv", header=None)
df.to_csv("results.csv", header=["Raw"], index=False)
df = pd.read_csv("results.csv")
ft = df["Raw"].value_counts(sort=False)
ft.to_csv('Data_Count.csv')
I want the final product to look like:
Distances Frequency
1 1
2 3
3 2
4 1
5 2
It currently looks like:
Raw
1 1
2 3
3 2
4 1
5 2
Furthermore, is it possible to somehow condense this code so that only one file is created instead of two (This is not important and doesn't have to be answered)? For reference, the calculate(count) function looks like:
def calculate(n):
outputs = []
for i in range(0, n):
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if NUMBERS.index(num1) < NUMBERS.index(num2):
difference = subtract(num1, num2)
elif NUMBERS.index(num1) > NUMBERS.index(num2):
difference = distance(num1, num2)
else:
difference = 0
outputs.append([difference])
return outputs