1

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

1 Answer 1

1

Use Series.rename_axis for set index name with DataFrame.reset_index, last add index=False to to_csv for avoid write default RangeIndex:

ft = (df["Raw"].value_counts(sort=False)
               .rename_axis('Distances')
               .reset_index(name='Frequency'))
ft.to_csv('Data_Count.csv', index=False)
Sign up to request clarification or add additional context in comments.

1 Comment

Will that also produce the Frequency column name?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.