gpt4 book ai didi

Python Pandas Dataframe 用列表中的值替换 NaN

转载 作者:太空宇宙 更新时间:2023-11-04 02:13:53 26 4
gpt4 key购买 nike

我正在尝试用 NaN 替换我的列

group_choices = ['Group1', 'Group2', 'Group3']

Groups limit
1 NaN NaN
2 Group1 2
3 Group2 2
4 Group3 2
5 NaN NaN
6 NaN NaN
7 NaN NaN

如何根据 group_choises 随机替换 NaN?

由于限制列中的限制值,我还试图限制随机选择 group_choise 的频率。

我试图得到这个结果:

Groups limit
1 Group3 NaN
2 Group1 2
3 Group2 2
4 Group3 2
5 Group1 NaN
6 Group2 NaN
7 Out of groups

最佳答案

fillna 用字典

dct = dict(zip(df.Groups.loc[pd.isna].index, group_choices))

df.fillna({'Groups': dct}).fillna({'Groups': 'Out of groups'})

Groups limit
1 Group1 NaN
2 Group1 2.0
3 Group2 2.0
4 Group3 2.0
5 Group2 NaN
6 Group3 NaN
7 Out of groups NaN

旧答案

有用,但我更喜欢新的。它说明了我的思维过程的演变。

生成器

def get_some(i, n):
for x in [*i] * n:
yield x

def fill(s, i, n):
gs = get_some(i, n)
for x in s:
if pd.isnull(x):
try:
yield next(gs)
except StopIteration:
yield "Out of groups"
else:
yield x

df.assign(Groups=[*fill(df.Groups, group_choices, 1)])

Groups limit
1 Group1 NaN
2 Group1 2.0
3 Group2 2.0
4 Group3 2.0
5 Group2 NaN
6 Group3 NaN
7 Out of groups NaN

备选

def get_some(i, n):
for x in [*i] * n:
yield x

df.assign(Groups=df.Groups.fillna(
df.Groups.loc[pd.isna].pipe(
lambda s: pd.Series(dict(zip(s.index, get_some(group_choices, 1))))
)
).fillna('Out of groups'))

关于Python Pandas Dataframe 用列表中的值替换 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53087312/

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