1

I have a csv file like the following:

#1, #2, #3, #4, #5, #6

I want to generate a data frame using the read_csv method, but how do I assign the values in the first 5 columns to a single column in my data frame as a list? And how could I apply a heading to that column?

1 Answer 1

1

Create a new DataFrame.

Supposing your previous DataFrame object is df=read_csv('something.csv')

df1 = pd.DataFrame(columns=['ColName1','ColName2']) #new DataFrame with column Names as ColName1 and ColName2
c=0 #Index for new DataFrame
for i in range(len(df)):
    df1.loc[c] = [None for x in range(2)] #Row elements initially Null
    df1.loc[c].ColName1 = []
    for j in range(1,5):
        df1.loc[c].ColName1.append(df.loc[i]['#' + str(j)])
    df1.loc[c].ColName2 = df.loc[i]['#6']
    c += 1
df1.to_csv('new.csv')
Sign up to request clarification or add additional context in comments.

4 Comments

Is there no way to simply do that in a call to the read_csv function as parameters?
You can, but to be honest, it's not that simple.
Could I see it for my own curiosity?
Yes please. I just want to see how it would be done using that function.

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.