gpt4 book ai didi

python - 将数据从一列回填到另一列

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

这就是我的数据的样子:

colA  colB
a 1
a 1
c 2
c 2
Nan 1
c 1
a 2
Nan 2

我想把 Nans 填入 colA 中。结果应如下所示:

colA  colB
a 1
a 1
c 2
c 2
a 1
c 1
a 2
c 2

第 5 行填充了“a”,因为 colB = 1 并且 colB 中的总体 1 已映射到比 colA 中的 c 更多的 a

第 8 行填充了“c”,因为 colB = 2 并且 colB 中的总体 2 已映射到比 colA 中的 a 更多的 c

最佳答案

您可以使用mode (忽略抽签)各组:

In [11]: df
Out[11]:
colA colB
0 a 1
1 a 1
2 c 2
3 c 2
4 NaN 1
5 c 1
6 a 2
7 NaN 2

In [12]: modes = df.groupby('colB')['colA'].transform(lambda x: x.mode().iloc[0])

In [13]: modes
Out[13]:
0 a
1 a
2 c
3 c
4 a
5 a
6 c
7 c
Name: colA, dtype: object

使用 fillna 仅替换 NaN 的模式:

In [14]: df['colA'].fillna(modes)
Out[14]:
0 a
1 a
2 c
3 c
4 a
5 c
6 a
7 c
Name: colA, dtype: object

In [15]: df['colA'] = df['colA'].fillna(modes)
<小时/>

注意:阅读文档,如果没有任何项目至少出现一次,则会引发此错误,因此您可能希望在转换中使用更强大的函数:

def mymode(s):
try:
return s.mode().iloc[0]
except IndexError:
# just pick the first element, even though it occurs only once, even if it's NaN
return s.iloc[0] if len(s) >= 1 else np.nan

关于python - 将数据从一列回填到另一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29116286/

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