简体   繁体   English

如何将pandas列分配给其他列,或者如果为nan,则为默认值?

[英]How to assign pandas column to other column, or default value if nan?

I have我有

df = df =

a
1
nan
3

I want some syntax for我想要一些语法

df["b"] = df["a"] or 5

to create创造

a     b
1     1
nan   5
3     3

Does pandas support something like this?熊猫是否支持这样的东西?

BONUS:奖金:

what about different default values per index/group/anything?每个索引/组/任何东西的不同默认值怎么样?

import pandas as pd
import numpy as np


df = pd.DataFrame({"a": [1, np.nan, 3]})
df["b"] = df["a"].fillna(5)
print(df)
 ab 0 1.0 1.0 1 NaN 5.0 2 3.0 3.0

digging through the doc gave the standard pandas solution.通过文档挖掘给出了标准的熊猫解决方案。 No need to go through numpy.无需通过 numpy.

You can use np.where你可以使用np.where

df['b'] = np.where(df['a'].isna(), 5, df['a'])
print(df)

     a    b
0  1.0  1.0
1  NaN  5.0
2  3.0  3.0

您可以applymap()使用applymap()函数甚至factorize()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM