Python Forum
Question from beginners: how to combine 2 columns
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question from beginners: how to combine 2 columns
#1
Hi guys,
I have one table with a lot of columns: Two of them are Start Station and End Station

Start Station
0 Columbus Dr & Randolph St
1 Kingsbury St & Erie St
2 Canal St & Madison St
3 Spaulding Ave & Armitage Ave
4 Clark St & Randolph St


End Station \
Federal St & Polk St
Orleans St & Merchandise Mart Plaza
Paulina Ave & North Ave
California Ave & Milwaukee Ave
Financial Pl & Congress Pkwy

Now I want to display the most frequent combination of start station and end station trip

This is my code:
import pandas as pd
df = pd.read_csv('chicago.csv')
# I exctract the column with start stations:
x= df.iloc[:, 3]
# I exctract the column with end stations:
y =df.iloc[:, 4]
# Put this two columns together and 
df2 = (x+' & '+y)
#display the most frequent combination of start station and end station trip
df1 = df.groupby(df2).count().sorted(df2)
print (df1)
However, the code doesn't work.
This is what I get
 'DataFrame' object has no attribute 'sorted'
Actually I excpected smth like this:
Columbus Dr & Randolph St & Federal St & Polk St 8

How can I fix it?
Thanks
J
Reply
#2
There is no reason to use Pandas on a simple task like this. You can just read the csv file normally.


with open('chicago.csv', 'r') as fp:
    for rec in fp:
        split_rec=rec.strip().split(",")
        ## you now have a list of columns and can use a 
        ## dictionary to count the 2 combined columns
        print(split_rec)

        ## ****** I am not going to do your homework for you ***** 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PyTorch for beginners OmegaRed94 1 1,058 Jun-09-2022, 09:20 PM
Last Post: Larz60+
  pandas.to_datetime: Combine data from 2 columns ju21878436312 1 2,418 Feb-20-2021, 08:25 PM
Last Post: perfringo
  Grab columns from multiple files, combine into one jon0852 0 2,004 Feb-12-2019, 02:53 AM
Last Post: jon0852

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020