Python Forum
Substring and If then Condition to create column
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Substring and If then Condition to create column
#2
Try this to see if that helps,

import pandas as pd

df=pd.read_csv("ab.csv",header=0, names=['roadno'])
print(df)
data=[] 
for i in df['roadno']:
	if i[:1].lower()=="h" or i[:1].lower()=="m":   #if i[:1].lower() in ('h','m'):
		data.append("MAIN road")
	else:
		data.append("other road")
print(data)
df["new column"]=data
print(df)
Output:
python test2.py roadno 0 H001 1 H0002 2 M002 3 M03050 4 A001 5 B002 6 C002 7 F002 8 5001 9 8002 ['MAIN road', 'MAIN road', 'MAIN road', 'MAIN road', 'other road', 'other road', 'other road', 'other road', 'other road', 'other road'] roadno new column 0 H001 MAIN road 1 H0002 MAIN road 2 M002 MAIN road 3 M03050 MAIN road 4 A001 other road 5 B002 other road 6 C002 other road 7 F002 other road 8 5001 other road 9 8002 other road
Best Regards,
Sandeep

GANGA SANDEEP KUMAR
Reply


Messages In This Thread
RE: Substring and If then Condition to create column - by sandeep_ganga - Jan-23-2020, 08:35 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Get an average of the unique values of a column with group by condition and assign it klllmmm 0 582 Feb-17-2024, 05:53 PM
Last Post: klllmmm
  Python Alteryx QS-Passing pandas dataframe column inside SQL query where condition sanky1990 0 868 Dec-04-2023, 09:48 PM
Last Post: sanky1990
  extract substring from a string before a word !! evilcode1 3 713 Nov-08-2023, 12:18 AM
Last Post: evilcode1
  [SOLVED] [regex] Why isn't possible substring ignored? Winfried 4 1,255 Apr-08-2023, 06:36 PM
Last Post: Winfried
  create new column based on condition arvin 12 2,641 Dec-13-2022, 04:53 PM
Last Post: jefsummers
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 986 Sep-08-2022, 06:32 AM
Last Post: klllmmm
  ValueError: substring not found nby2001 4 8,309 Aug-08-2022, 11:16 AM
Last Post: rob101
  Match substring using regex Pavel_47 6 1,612 Jul-18-2022, 07:46 AM
Last Post: Pavel_47
  Python create a spreadsheet with column and row header ouruslife 4 1,898 Jul-09-2022, 11:01 AM
Last Post: Pedroski55
  Cannot convert the series to <class 'int'> when trying to create new dataframe column Mark17 3 8,889 Jan-20-2022, 05:15 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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