[英]Adding Column to pandas DataFrame in Vectorized way conditioning on other column values
[英]Using pandas "where" change values of an entry conditioning on all values in the column
问题建模:
假设我们有数据框
DF = pd.DataFrame({'a' : [ 3, 0, 1, 0, 1, 14, 2, 0, 0, 0, 0],
'b' : [ 3, 0, 1, 0, 1, 14, 2, 0, 0, 0, 0],
'c' : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'd' : [5, 1, 2 ,1, 1 ,22, 30, 1, 0, 0, 0]})
只有当特定列中的所有值都为零时,我们才希望将 0 更改为 100。 在我们的例子中,这是“c”列。
最后我们会有
'a' : [ 3, 0, 1, 0, 1, 14, 2, 0, 0, 0, 0],
'b' : [ 3, 0, 1, 0, 1, 14, 2, 0, 0, 0, 0],
'c' : [ 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
'd' : [5, 1, 2 ,1, 1 ,22, 30, 1, 0, 0, 0]})
我在考虑DF.where(...)
但很难设置正确的条件。 可能还有另一种方式。
您可以使用.all()
和.loc
,例如:
DF.loc[:, DF.eq(0).all()] = 100
import numpy as np
import pandas as pd
df = pd.DataFrame({'a' : [ 3, 0, 1, 0, 1, 14, 2, 0, 0, 0, 0],
'b' : [ 3, 0, 1, 0, 1, 14, 2, 0, 0, 0, 0],
'c' : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'd' : [5, 1, 2 ,1, 1 ,22, 30, 1, 0, 0, 0]})
for column in df.columns:
if (df[column]==0).all():
df[column] = 100
mrzo 的解决方案很优雅,但问题在于您必须将其应用于包括 C 本身在内的所有列。 下面的解决方案应该允许您准确选择这应该适用于哪些列:
import numpy as np
import pandas as pd
df = pd.DataFrame({'a' : [ 3, 0, 1, 0, 1, 14, 2, 0, 0, 0, 0],
'b' : [ 3, 0, 1, 0, 1, 14, 2, 0, 0, 0, 0],
'c' : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'd' : [5, 1, 2 ,1, 1 ,22, 30, 1, 0, 0, 0]})
df['SUM'] = df['a'] + df['b'] + df['d']
df['c'] = df['SUM'].apply(lambda x: 100 if x>0 else x)
df
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.