Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Python Splitting column into 2

Eclipse

New Coder
So I'm working on a deliverable assignment for my bootcamp, I'm trying to split the "name" column into "first_name" and "last_name"

In the image below (in the spoiler tag):
The first cell is the dataframe
The one below it is my code with the error

1665787292254.png
 
Maybe something like this
Python:
import pandas as pd #import pandas
file = 'test.csv' # Name of csv file
path = __file__.split('/') # Get executing file a list
path.pop(len(path)-1) # Pop off the executing file
path = '/'.join(path) # Join the path of executing folder/directory
path = path + f'/{file}' # Add csv file
data = pd.read_csv(path) # Read csv into pandas
fname = [] # Create a list to hold first names
lname = [] # Create a list to hold last names
for name in data['name']: # Loop through dataframe name column
    name = name.split() # split the names
    fname.append(name[0].strip()) # Append first name to fname list
    lname.append(name[1].strip()) # Append last name to lname list
data.rename(columns={'name':'first name'},inplace=True) # Rename the name column to first name
data.insert(3, 'last name', '') # Insert at index 3 new column name (last name)
data['last name'] = lname # Add lname list to last name column
data['first name'] = fname # Add fname list to first name column
print(data) # Print new dataframe

output
Code:
  backer_id  cf_id first name last name               email
0     av166    968     Angelo   Vincent   [email protected]
1     ha127    563     Hubert    Arnold  [email protected]
2    ace123    544       John       Doe       [email protected]
 
Last edited:
Back
Top Bottom