473,395 Members | 1,694 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

using substring and if elif condition to create new column

Hi There,
I am new to python so please be kind to me.
Below is the data frame and the requirement:
Expand|Select|Wrap|Line Numbers
  1. data = {'id': ['aa11bc', 'bb22cd', 'cc33ef', 'dd44gh', 'ee55ij','ff66kl','gg77mn','hh88op'], 
  2.         'direction': ["north, south, east, west", "north, south, east, west", "north, south/, *east, \west%", "north, south, east, west",
  3.                       "north, south, east, west","north, south, east, west","north, south, east, west"
  4.                      ,"north, south, east, west"]}
  5. df = pd.DataFrame(data, columns = ['id','direction'])
  6. df
  7.  
  8. Requirement:
  9. #if id (2nd and 3rd letter) in ('a1','b2') then new_col should have north as an observation from direction column
  10. #else if id (2nd and 3rd letter) in ('c3','d4') then new_col should have south as an observation from direction column
  11. #else if id (2nd and 3rd letter) in ('e5','f6') then new_col should have east as an observation from direction column
  12. #else if id (2nd and 3rd letter) in ('g7','h8') then new_col should have west as an observation from direction column
I tried with the below code: but the output is not correct it's not meeting the desired output.

Expand|Select|Wrap|Line Numbers
  1. new_col=[]
  2.  
  3. for i in df["id"]:
  4.     if i[1:3].lower()in ('a1','b2'):
  5.         new_col=df["direction"].str.split(',').str[0].str.replace('\W+',' ').str.strip()
  6.     elif i[1:3].lower()in ('c3','d4'):
  7.         new_col=df["direction"].str.split(',').str[1].str.replace('\W+',' ').str.strip()
  8.     elif i[1:3].lower()in ('e5','f6'):
  9.         new_col=df["direction"].str.split(',').str[2].str.replace('\W+',' ').str.strip()
  10.     elif i[1:3].lower()in ('g7','h8'):
  11.         new_col=df["direction"].str.split(',').str[3].str.replace('\W+',' ').str.strip()
  12.  
  13. df["position"]=new_col
  14. print(df)
  15.  
  16. And the output as follows:
  17.        id                     direction position
  18. 0  aa11bc      north, south, east, west     west
  19. 1  bb22cd      north, south, east, west     west
  20. 2  cc33ef  north, south/, *east, \west%     west
  21. 3  dd44gh      north, south, east, west     west
  22. 4  ee55ij      north, south, east, west     west
  23. 5  ff66kl      north, south, east, west     west
  24. 6  gg77mn      north, south, east, west     west
  25. 7  hh88op      north, south, east, west     west
Please advise.
Feb 14 '20 #1

✓ answered by SioSio

I didn't understand what you wanted to do, but is that OK?
Do you need to replace non-alphabets in direction?
Expand|Select|Wrap|Line Numbers
  1. new_col=[]
  2. j = 0
  3. for i in df["id"]:
  4.     if i[1:3].lower()in ('a1','b2'):
  5.         new_col.append(re.sub(r'\W+','',df.loc[j, 'direction'].split(',')[0]))
  6.     elif i[1:3].lower()in ('c3','d4'):
  7.         new_col.append(re.sub(r'\W+','',df.loc[j, 'direction'].split(',')[1]))
  8.     elif i[1:3].lower()in ('e5','f6'):
  9.         new_col.append(re.sub(r'\W+','',df.loc[j, 'direction'].split(',')[2]))
  10.     elif i[1:3].lower()in ('g7','h8'):
  11.         new_col.append(re.sub(r'\W+','',df.loc[j, 'direction'].split(',')[3]))
  12.     j = j + 1
  13. df ["position"] = new_col
  14. print(df)
  15.  

3 1926
SioSio
272 256MB
I didn't understand what you wanted to do, but is that OK?
Do you need to replace non-alphabets in direction?
Expand|Select|Wrap|Line Numbers
  1. new_col=[]
  2. j = 0
  3. for i in df["id"]:
  4.     if i[1:3].lower()in ('a1','b2'):
  5.         new_col.append(re.sub(r'\W+','',df.loc[j, 'direction'].split(',')[0]))
  6.     elif i[1:3].lower()in ('c3','d4'):
  7.         new_col.append(re.sub(r'\W+','',df.loc[j, 'direction'].split(',')[1]))
  8.     elif i[1:3].lower()in ('e5','f6'):
  9.         new_col.append(re.sub(r'\W+','',df.loc[j, 'direction'].split(',')[2]))
  10.     elif i[1:3].lower()in ('g7','h8'):
  11.         new_col.append(re.sub(r'\W+','',df.loc[j, 'direction'].split(',')[3]))
  12.     j = j + 1
  13. df ["position"] = new_col
  14. print(df)
  15.  
Feb 14 '20 #2
Hi There,
Thanks for the help.
Yes, I am getting the desired output from your code.
I want to try one more condition from your code, I let you know the status. Until such time I will keep this question as open.
Hope this is fine with you.
Once again thanks for your help.
Cheers!!
Feb 14 '20 #3
HI SioSio,
Thanks for the help with the code.
Feb 15 '20 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Tricon | last post by:
Is there a way to create a colum from values in a row? For example, Let's say I have the following: 12345 Bigfoot 1 $1.00 12345 Bigfoot 2 $2.00 12345 Bigfoot ...
2
by: Jake Barnes | last post by:
Using javascript closures to create singletons to ensure the survival of a reference to an HTML block when removeChild() may remove the last reference to the block and thus destory the block is...
4
by: loydbrahn | last post by:
I have a SQL Table I am trying to update...I would like to add '-000' to the end of every value in a column, GLSegment. I can do this for one row using this statement... UPDATE...
1
by: josh24 | last post by:
In MS SQL Server I need to update a substring of data within a column based on a change to two parts of the string. The column accountcode exists currently as: 0100-0001 I need to change...
4
by: Jean-François Michaud | last post by:
Hello, I've been looking at this for a bit now and I don't see what's wrong with the code. Can anybody see a problem with this? Here is an XSLT snippet I use. <xsl:template match="graphic">...
2
by: =?Utf-8?B?TWlrZSBE?= | last post by:
Is it possible to retreive groups from a sub-OU by using substring? I need to be able to loop over the OUs of a OU to see if any have a sub-OU whose Name ends with 'Security Groups' and output the...
2
by: rahullko05 | last post by:
I want to add a check condition to the column. I use the following script DROP TABLE IF EXISTS `Customer`; CREATE TABLE `Customer` ( `CustomerId` INT UNSIGNED NOT NULL UNIQUE AUTO_INCREMENT...
2
by: Chandan Kr Sah | last post by:
How to write sql query to create column of type Yes/No with checkbox.By default it is creating with textbox. I am struglling for the same from one week. So plese provide me any solution for the...
4
by: Octo Siburian | last post by:
Hii all, i have a problem to get every second row in a table with condition 1 column has a same value, example: i have 1 table is called 'HP' with column id,nik,hp,status_aktif id | nik |...
1
by: sakura | last post by:
Hi. I'm using asp.net and c# language. How can i display a GridView using select statement of two column in one table? This is my coding: if (sdr.Read()) { if(namaPembekal.Equals(sdr)...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.