gpt4 book ai didi

python - pandas 如何根据其他列填充 NaN/None 值?

转载 作者:太空宇宙 更新时间:2023-11-03 17:13:19 25 4
gpt4 key购买 nike

鉴于以下情况,如何根据其他行设置 B 行的 NaN/None 值?我应该使用应用吗?

d = [
{'A': 2, 'B': Decimal('628.00'), 'C': 1, 'D': 'blue'},
{'A': 1, 'B': None, 'C': 3, 'D': 'orange'},
{'A': 3, 'B': None, 'C': 1, 'D': 'orange'},
{'A': 2, 'B': Decimal('575.00'), 'C': 2, 'D': 'blue'},
{'A': 4, 'B': None, 'C': 1, 'D': 'blue'},
]

df = pd.DataFrame(d)

# Make sure types are correct
df['B'] = df['B'].astype('float')
df['C'] = df['C'].astype('int')

In : df
Out:
A B C D
0 2 628 1 blue
1 1 NaN 3 orange
2 3 NaN 1 orange
3 2 575 2 blue
4 4 NaN 1 blue

In : df.dtypes
Out:
A int64
B float64
C int64
D object
dtype: object

以下是当值为 None 时设置 B 的“规则”示例:

def make_B(c, d):
"""When B is None, the value of B depends on C and D."""
if d == 'blue':
return Decimal('1400.89') * 1 * c
elif d == 'orange':
return Decimal('2300.57') * 2 * c
raise

最佳答案

这是我解决这个问题的方法:

我定义make_B如下:

def make_B(x):
if np.isnan(x['B']):
"""When B is None, the value of B depends on C and D."""
if x['D'] == 'blue':
return Decimal('1400.89') * 1 * x['C']
elif x['D'] == 'orange':
return Decimal('2300.57') * 2 * x['C']
else:
return x['B']

然后我使用应用:

df.apply(make_B,axis=1)

关于python - pandas 如何根据其他列填充 NaN/None 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33883200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com