I have a pandas data frame and creating new column out of existing column values with'-' separator
I am trying this below code its not working as expected.
data["{}_pid".format(granularity)] = data[config['compute_hierarchy'][granularity]].apply(lambda x: x.str.cat(sep='-') if x.granularity != None, axis=1 )
ex: if i have column value as a,b,c then new column value is a-b-c and if any column value is null then lambda function should not execute
"if" keyword "directly" (I'm being vague) in a lambda can only be part of a ternary operator.
So this lambda :
l1 = lambda x: "yes" if x else "no"
is correct, while this one :
l2 = lambda x: "yes" if x
is not.
If without else can be part of an expression in a list comprehension :
[print(a) for a in range(10) if a % 2]
Related
How can I apply lambda to echa element of list in a row?
I have a column with list of 2 elements in each row.
Those elelemts are strings and I want to make them ints.
Now: ['111', '222'] Then: [111, 222]
How to pass iteration thru each element of a list in a row?
df.column.apply(lambda x: int(x) for x in...
And I'm stuck here not knowing how to iterate since I already told lambda to work with x where x is a certain cell.
Thank you in advance.
Data Sample screenshot enclosed.enter image description here
The problem is with 'coords' column.
SOLVED:
I don't know why but this worked:
df.column.apply(lambda x: (float(x[0]), float(x[1])) if pd.isna([x]).any() == False else x)
Have you tried indexing into the list?
df.column.apply(lambda x: [int(x[0]), int(x[1])] for x in...
EDIT:
As your column sometimes contains None, try this:
df.column.apply(lambda x: x if pd.isnull(x) else [int(x[0]), int(x[1])]
This assumes that the problem values are None and not something like ['111', None]
Leaving out the lead-up and data to the following because it looks like an error in how the list comprehension is written. It is meant to cycle through a list l of pandas DataFrames and Series, and label them based on whether they are two dimensional (both index and columns) or one dimensional (index only). Why the error (even if a close the line-break)?
[pd.DataFrame(A, index=labels, columns=labels) for A in l
if type(A) is pd.DataFrame else pd.Series(A, index=labels)]
results in
if type(A) is pd.DataFrame else pd.Series(A, index=tickers)]
^
SyntaxError: invalid syntax
You need to move the for A in l to the end of your statement.
[pd.DataFrame(A, index=labels, columns=labels) if type(A) is pd.DataFrame else pd.Series(A, index=labels) for A in l]
See: Is it possible to use 'else' in a list comprehension?
Is you issue is not due to the is.
Maybe try with isinstance(type(A) , pd.DataFrame)
Another point is the order of your list compréhension if think it should be
[f(x) if condition else g(x) for x in sequence]
So you can try
[pd.DataFrame(A, index=labels, columns=labels) if isinstance(type(A) , pd.DataFrame) else pd.Series(A, index=labels) for A in l ]
I have an existing dictionary and I want to add new element as a first-class function generated from a list.
Is there a more pythonic way of doing this?
agg_dict = {}
for x in attribute_list:
agg_dict[x] = lambda x: ','.join(x)
I've tried using the list comprehensive and it doesn't work.
[agg_dict[x] = lambda x: ','.join(x) for x in attribute_list]
First of all, it should be agg_dict[x], not agg_dict['x']. Also, you can just use a dict comprehension:
agg_dict = {x: lambda arg: ','.join(arg) for x in attribute_list}
Need to filter lambda function so that it can give only even result. please help i am a beginner.
list_one = [1,2,3,4]
list_two = [5,6,7,8]
a = lambda *b :[sum(j)/len(j) for j in zip(*b)]
output-->[5,6,7,8] without applying filter
b = filter((a % 2 == 0),(list_one,list_two))
want output [6,8] after applying filter method
You need to pass a function and an iterable to the filter.
the function is filtering elements that match a condition.
The iterable is the output of a:
b = filter(lambda e: e%2==0, a(list_one, list_two))
languages = ["HTML", "JavaScript", "Python", "Ruby"]
Hi, I'm trying to learn about lambda in python and I'm wondering if I want to filter onto just the 'Python' list item, why can't i just use
print filter(lambda x: x[2], languages)
which still returns the entire list, and have to use
print filter(lambda x: x == 'Python', languages)
Thanks!
When you are applying filter function, you have to give a condition which when satisfied returns the value.
print filter(lambda x: x[2], languages)
In first filter, x[2] will be true in each case as X gets values HTML so, x[2] will be M and so on. That's why it is giving all values.
While in second case,you have given the condition x == 'Python' so it will give you the proper result.
Imagine the filter as a for loop.
print filter(lambda x: x[2], languages) is equivalent to
result = []
for x in languages:
if x[2]:
result.append(x)
print result
Notice that instead of calling languages[2], which is Python, this calls x[2], which evaluates as if 'M': for 'HTML', if 'v' for 'Javascript', and so on—since these strings are all non-empty, they are evaluated as True, and thus added to result.
Instead, print filter(lambda x: x == 'Python', languages) is equivalent to
result = []
for x in languages:
if x == 'Python':
result.append(x)
print result
Which loops over languages, appending items that match 'Python', which is the desired effect.
To filter out 'Python' use != (not equals) operator as follows.
print filter(lambda x: x != 'Python', languages)
why don't you use list comprehensions for it?
languages = ["HTML", "JavaScript", "Python", "Ruby"]
languages=[ lang for lang in languages if lang=='Python']
print languages
output would be
['Python']
It's more cleaner and faster than filter , given you are using lambda with it, for more info