Hi There,
I am new to python so please be kind to me.
I am learning the substring function, so I am just trying different cases to get familiar.
I have managed to get the output for a single substring function. However when I apply multiple conditions then I get the following error. Appreciate if you guys educate me on this. - data = {'name': ['John', 'Aaron', 'Anie', 'Nancy', 'Steve'],
-
'Gender': ['00M00','00M00','00F00','00F00','00x00'],
-
'Dept': ['01MK00', '02FN00', '03LG00', '04HR00', '05DR00']}
-
df = pd.DataFrame(data, columns = ['name', 'Gender', 'Dept'])
-
df
-
-
-
var=[]
-
-
for i in df["Gender"]:
-
for x in df["Dept"]:
-
-
if i[2].lower()=='m' & x[2:4].lower()=='mk':
-
var.append('Male in Marketing')
-
-
elif i[2].lower()=='f' & x[2:4].lower()=='fn':
-
var.append('Female in Finance')
-
-
else:
-
var.append('Others')
-
- Error message below
-
File "<ipython-input-79-ff06a7e562be>", line 4
-
for x in df["Dept"]:
-
^
-
IndentationError: expected an indented block
-
-
Regards,
CK
7 3284
If you just want to fix the error in this code: - import pandas as pd
-
-
data = {'name': ['John', 'Aaron', 'Anie', 'Nancy', 'Steve'],
-
'Gender': ['00M00','00M00','00F00','00F00','00x00'],
-
'Dept': ['01MK00', '02FN00', '03LG00', '04HR00', '05DR00']}
-
df = pd.DataFrame(data, columns = ['name', 'Gender', 'Dept'])
-
df
-
-
-
var=[]
-
-
for i in df["Gender"]:
-
for x in df["Dept"]:
-
-
if i[2].lower() in 'm' and x[2:4].lower() in 'mk':
-
var.append('Male in Marketing')
-
elif i[2].lower()in 'f' and x[2:4].lower() in 'fn':
-
var.append('Female in Finance')
-
else:
-
var.append('Others')
-
Hi There,
Thanks for this,
However, still, I am getting the following error after running the above code:
Is there any better way to enhance the code to get the right output. -
-
-
var=[]
-
-
for i in df["Gender"]:
-
for x in df["Dept"]:
-
-
if i[2].lower() in 'm' and x[2:4].lower() in 'mk':
-
var.append('Male in Marketing')
-
elif i[2].lower()in 'f' and x[2:4].lower() in 'fn':
-
var.append('Female in Finance')
-
else:
-
var.append('Others')
-
-
df["new_col"]=var
-
df.head()
-
- Error message below
-
-
-
ValueError Traceback (most recent call last)
-
<ipython-input-93-dd3e254bfbaf> in <module>
-
----> 1 df["new_col"]=var
-
2 df.head(5)
-
-
H:\Softwares\PythonSoftware\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
-
2936 else:
-
2937 # set column
-
-> 2938 self._set_item(key, value)
-
2939
-
2940 def _setitem_slice(self, key, value):
-
-
H:\Softwares\PythonSoftware\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value)
-
2998
-
2999 self._ensure_valid_index(value)
-
-> 3000 value = self._sanitize_column(key, value)
-
3001 NDFrame._set_item(self, key, value)
-
3002
-
-
H:\Softwares\PythonSoftware\lib\site-packages\pandas\core\frame.py in _sanitize_column(self, key, value, broadcast)
-
3634
-
3635 # turn me into an ndarray
-
-> 3636 value = sanitize_index(value, self.index, copy=False)
-
3637 if not isinstance(value, (np.ndarray, Index)):
-
3638 if isinstance(value, list) and len(value) > 0:
-
-
H:\Softwares\PythonSoftware\lib\site-packages\pandas\core\internals\construction.py in sanitize_index(data, index, copy)
-
609
-
610 if len(data) != len(index):
-
--> 611 raise ValueError("Length of values does not match length of index")
-
612
-
613 if isinstance(data, ABCIndexClass) and not copy:
-
-
ValueError: Length of values does not match length of index
-
Error Message: "Value length does not match index length"
The array size of df is 5, but var is 5x5 = 25.
Hi There,
Is there any workaround to satisfy the above condition.
It can use the built-in function zip() to get the values of multiple columns at once. - for Gender, Dept in zip(df['Gender'], df['Dept']):
-
if Gender[2].lower() in 'm' and Dept[2:4].lower() in 'mk':
-
var.append('Male in Marketing')
-
elif Gender[2].lower()in 'f' and Dept[2:4].lower() in 'fn':
-
var.append('Female in Finance')
-
else:
-
var.append('Others')
-
HI SioSio,
Thanks for the advice and help with this.
Kind regards,
CK
The ValueError: Length of values does not match length of index raised because the previous columns you have added in the DataFrame are not the same length as the most recent one you have attempted to add in the DataFrame. So, you need make sure that the length of the array you are assign to a new column is equal to the length of the dataframe .
The simple solution is that you first convert the list/array to a pandas Series , and then when you do assignment, missing index in the Series will be filled with NaN values . - df = pd.DataFrame({'X': [1,2,3,4]})
-
df['Y'] = pd.Series([3,4])
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Radhika Sambamurti |
last post by:
Hi,
I've written a substring function.
The prototype is: int substr(char s1, char s2)
Returns 1 if s2 is a substring of s1, else it returns 0.
I have written this program, but Im sure there is an easier way to do this. I am hoping someone can point me to a more elegant way of writing this same function.
//// code follows ///////////
//implement a substring function, where if string2 is a sub of string 1, then the value returned is 1...
|
by: ammarton |
last post by:
Hello all...I'm a bit new to working with Macros in Access so forgive
me if the terminology I use is not accurate.
To preface this, basically I am using a form on a replicated database
so the end-user can filter on a specific report they want to see. This
database was designed by my predecessor (of which he left no
documentation) and I need to add some additional functions to this
end-user filter report.
Within one Macro, he has over...
|
by: booksnore |
last post by:
..eh I was stuck thinking up a subject title for this post for a while..
So I am processing a really big file (scary big). Each record is fixed
length, I need to test conditions on certain fields in the record. At
the moment the most efficient way I've found to process the data is a
series of nested if/else statements so like below. My question is does
anyone know of a better way to process this kind of logic. I can't use a
switch...
|
by: Shailja |
last post by:
Kindly tell me how to use Substring function in VB.
|
by: Rocky86 |
last post by:
anybody know how to do a substring function in actionscript pls help~!! I want to do something like extact the number out and convert it to string!
| |
by: ashokbio |
last post by:
How to return multiple values by passing multiple arguments in function or subroutine using VB6?
T. Ashok Kumar
|
by: ponvijaya |
last post by:
Hi all,
I have used a substring function inside my stored procedre as
set @dummy1=substring(@dummyid,2);
but when i print and check the value of @dummy1 as
select @dummy1;
|
by: obanite |
last post by:
Hello,
Is there a better way of doing:
<xsl:variable name="frlink">
<xsl:choose>
<xsl:when test="@isFriend = '0'"><xsl:value-of select="concat('friends.php?add=', @uid)"/></xsl:when>
<xsl:otherwise> <xsl:value-of select="concat('friends.php?add=', @uid)"/></xsl:otherwise>
</xsl:choose>
</xsl:variable>
|
by: pnunbe |
last post by:
Hi,
I have a problem with the 'substring' function of XPath in VB.NET (VS 2005).
My code looks like this:
dim Dom As new XmlDocument
Dim mgr As New XmlNamespaceManager(Dom.NameTable)
'mgr.AddNamespace("fn", "http://www.w3.org/2005/xpath-functions/#substring")
mgr.AddNamespace("fn", "http://www.w3.org/2005/xpath-functions")
|
by: rhuseman |
last post by:
On my form I have 24 combo boxes ( 12 of which are conditional/cascading combo boxes dependent on the users input of the other 12 combo boxes).
I've found ways to do it by code each individual combo box ( http://stackoverflow.com/questions/7624318/vb-net-cascading-comboboxes-connected-to-dataset-from-access-changing-units). But I would really like to lean the code out and have it all in one spot.
I was thinking about putting this code...
|
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |