gpt4 book ai didi

python - 将 pandas 数据框中的 notnull 值替换为列表中的值/如何获取 notnull 值的索引/ bool 索引的实现

转载 作者:行者123 更新时间:2023-12-01 03:09:53 27 4
gpt4 key购买 nike

我对一个相当笨拙的标题表示歉意,我刚刚从我的具体问题中得到了更通用的问题,我认为这是问题的核心。简单地说,我有一个数据框和一个长度与列数或行数相同的列表。我想用列表中的相应值替换数据框中的 notnull 值。

示例如下:输入数据框:

          a         b         c         d
a 0.547825 NaN NaN 0.950158
b NaN 0.663845 0.529115 NaN
c NaN NaN NaN 0.685002
d NaN 0.791249 0.574452 0.734804

输入列表:[1,2,3,4]

期望的输出:

          a         b         c         d
a 1 NaN NaN 4
b NaN 2 3 NaN
c NaN NaN NaN 4
d NaN 2 3 4

这是目前我的代码:

frame = pd.DataFrame(np.random.rand(4,4),index=['a','b','c','d'], columns=['a','b','c','d'])
frame = np.asarray(frame)
frame[frame<0.5] = np.nan
frame = pd.DataFrame(frame,index=['a','b','c','d'], columns=['a','b','c','d'])

result = np.zeros((4,4))
result = pd.DataFrame(result, index=['A','B','C','D'], columns=['A','B','C','D'])
Somenums = [1,2,3,4]

for i, col in enumerate(frame.columns.values):
print frame[col]
print np.isfinite(frame[col])
mask = frame.ix[np.isfinite(frame[col]),col]
print mask
print Somenums[mask]
result.iloc[:,i] = Somenums[mask]
print result

但我收到:

TypeError                                 Traceback (most recent call last)
<ipython-input-34-c95f4f5ee05b> in <module>()
24 mask = frame.ix[np.isfinite(frame[col]),col]
25 print mask
---> 26 print Somenums[mask]
27 result.iloc[:,i] = Somenums[mask]
28 print result

TypeError: list indices must be integers, not Series

如何正确索引它/正确应用蒙版?

最佳答案

似乎发生错误是因为“掩码”是数据系列而不是索引或 bool 值。我能想到的一种方法是,代替 for 循环,执行以下操作:

idx = frame.notnull()
result = idx * Somenums
result[~idx] = None

如果您不介意用零来替换输出中的 nan,您可以这样做:

result = frame.notnull() * Somenums

关于python - 将 pandas 数据框中的 notnull 值替换为列表中的值/如何获取 notnull 值的索引/ bool 索引的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42965948/

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