- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个基本数据框,然后我想填充某些索引和列,这些索引和列由第二个数据框定义,我想影响基本 df 中的更改。第二个数据帧的索引 df_idx 是我感兴趣的 base_df 行; df_idx 还包含要填充的开始列和结束列,以及要写入的值。
base_df 看起来像这样:
import pandas as pd
import numpy as np
months = list(range(1, 13))
li = list(map(str, months))
cols = ['ID']
cols.extend(li)
df_base = pd.DataFrame(np.random.randint(0,1000,size=(5, 13)), columns=cols)
df_base.loc[[1,2],'1':'12'] = np.nan
df_base.loc[4,'7':'12'] = np.nan
ID 1 2 3 4 5 6 7 8 9 10 11 12
0 328 45.0 226.0 388.0 286.0 557.0 930.0 234.0 418.0 863.0 500.0 232.0 116.0
1 340 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 865 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
3 293 772.0 185.0 6.0 284.0 522.0 826.0 995.0 370.0 87.0 668.0 469.0 40.0
4 313 947.0 272.0 936.0 501.0 241.0 731.0 NaN NaN NaN NaN NaN NaN
下面的 df_idx 显示,对于索引 1,val 210 将沿 base_df 中从列 '1' 到列 '12' 的行填充:
df_idx = pd.DataFrame({'start': [1, 2, 3],
'end': [12, 10, 11],
'val':np.random.randint(0,1000,size=(1, 3))[0]},
index=[1,2,4])
start end val
1 1 12 210
2 2 10 663
4 3 11 922
我可以遍历行,我不想这样做,特别是因为 base_df 可能是 >250,000 行,如下所示:
for idx, row in df_idx.iterrows():
mntStrt = str(row['start'])
mnthEnd = str(row['end'])
df_base.loc[idx, mntStrt:mnthEnd] = row['val']
或者我现在倾向于使用 pandas 应用功能:
def inputVals(x):
idx = x.name
mntStrt = str(x['start'])
mnthEnd = str(x['end'])
df_base.loc[idx, mntStrt:mnthEnd] = x['val']
df_idx.apply(lambda x: inputVals(x), axis=1)
生成的数据框如下所示:
ID 1 2 3 4 5 6 7 8 9 10 11 12
0 947 537.0 827.0 477.0 39.0 586.0 370.0 576.0 556.0 119.0 158.0 990.0 958.0
1 157 129.0 129.0 129.0 129.0 129.0 129.0 129.0 129.0 129.0 129.0 129.0 129.0
2 545 NaN 849.0 849.0 849.0 849.0 849.0 849.0 849.0 849.0 849.0 NaN NaN
3 549 835.0 205.0 158.0 499.0 451.0 887.0 145.0 6.0 518.0 385.0 34.0 613.0
4 57 673.0 55.0 925.0 925.0 925.0 925.0 925.0 925.0 925.0 925.0 925.0 NaN
我觉得有一种更有效的方法来解决这个问题;任何见解或批评都将受到欢迎。谢谢!
最佳答案
一种方法是 reshape df_idx
以在索引为 df_idx
的数据帧中的正确位置以及所需列 1 到 12 中获取新值。为此,您可以使用 numpy 并将列开始和结束进行比较为 1 到 12。相乘通过 val 列并根据需要设置索引列。所以
# set sedd for reproductibility with df_idx
np.random.seed(1)
tmp = \
pd.DataFrame(
data = ((df_idx['start'].to_numpy()[:, None] <= np.arange(1,13))
& (df_idx['end'].to_numpy()[:, None] >= np.arange(1,13)))
*df_idx['val'].to_numpy()[:, None],
index=df_idx.index,
columns=li
).replace(0,np.nan) #
print(tmp)
1 2 3 4 5 6 7 8 9 10 11 12
1 37.0 37.0 37 37 37 37 37 37 37 37 37.0 37.0
2 NaN 235.0 235 235 235 235 235 235 235 235 NaN NaN
4 NaN NaN 908 908 908 908 908 908 908 908 908.0 NaN
现在您可以使用
update
在 df_base 中设置新值
df_base.update(tmp, overwrite=True) # no need of reassignment with update
# set overwrite = False if you only change the nan values in df_base to be updated
print(df_base)
ID 1 2 3 4 5 6 7 8 9 10 \
0 72 767.0 905.0 715.0 645.0 847.0 960.0 144.0 129.0 972.0 583.0
1 390 37.0 37.0 37.0 37.0 37.0 37.0 37.0 37.0 37.0 37.0
2 398 NaN 235.0 235.0 235.0 235.0 235.0 235.0 235.0 235.0 235.0
3 319 829.0 534.0 313.0 513.0 896.0 316.0 209.0 264.0 728.0 653.0
4 633 456.0 542.0 908.0 908.0 908.0 908.0 908.0 908.0 908.0 908.0
11 12
0 749.0 508.0
1 37.0 37.0
2 NaN NaN
3 627.0 431.0
4 908.0 NaN
关于python - 是否有更好的矢量化解决方案来使用在第二个数据帧中定义为变量的索引和列写入数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68377621/
据我所知,根本不为元素呈现 HTML,或添加 display:none,似乎具有完全相同的行为:两者都使元素消失并且不与 HTML 交互。 我正在尝试禁用和隐藏一个复选框。所以HTML的总量很小;我无
我刚刚读了Android Architecture Tutorial: Developing an App with a Background Service (using IPC) .基本上是 让服
我有两个查询具有相同的结果,现在我想知道哪个查询更优化? 在选择中: select t1.*, sum(t2.value) as total_votes from table1 t1 left joi
有人告诉我,对于 I/O 绑定(bind)的应用程序,非阻塞 I/O 会更好。对于 CPU 密集型应用程序,阻塞 I/O 会好得多。我找不到这种说法的原因。试过谷歌,但很少有文章只是触及这个话题而没有
我有一个算法可以在数字列表中寻找好的对。一个好的配对被认为是索引 i 小于 j 且 arr[i] 1: # Finding the mid of the array
我有一个算法可以在数字列表中寻找好的对。一个好的配对被认为是索引 i 小于 j 且 arr[i] 1: # Finding the mid of the array
我从 API 收到一个 json,我需要解析并修改一个属性值。问题是,我收到的 json 数据的嵌套结构不一致,我无法控制它。 这将禁止我指定在特定深度(如 parsedJson.children[0
我有 451 个城市的坐标。现在我想计算每个城市之间的距离,然后根据该距离对一些结果进行排序。现在我有两个选择: 我可以运行一个循环来计算每个可能的城市组合的距离并将它们存储到一个表中,这将产生大约
对于返回相同结果的不同查询,我有两个查询计划我想知道是否有人可以告诉我哪个“更好”,以及为什么。 SELECT * FROM bids order by (select ranking from us
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 7 年前。 Improve this qu
我有一个二维数组。我需要尽可能快地对其执行一些操作(函数每秒将被调用十几次,所以让它变得高效会很好)。 现在,假设我想获取元素 A[i][j],简单地使用 A[i][j] 在速度上有什么不同吗和 *(
在声明或使用字符串的代码中,我通常会看到开发人员这样声明它: string randomString = @"C:\Random\RandomFolder\ThisFile.xml"; 代替: str
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: Why don't CSS resets use '*' to cover all elements? 我正
如果我有一个包含许多重复项的 python 列表,并且我想遍历每个项目,而不是重复项,最好使用一个集合(如 set(mylist),或者找到另一种方法来创建没有重复的列表?我想只是循环遍历列表并检查重
在阅读常量接口(interface)反模式时,我发现没有实例的最终常量类比常量接口(interface)更好。 请解释一下怎么做? public interface ConstIfc { publ
我正在查看我继承的一些旧代码,我真的不喜欢某些地方的风格。我真的不喜欢它的外观的一件事是: bool func() { bool ret = true; ret &= test1();
关闭。这个问题是opinion-based 。目前不接受答案。 想要改进这个问题吗?更新问题,以便 editing this post 可以用事实和引文来回答它。 . 已关闭 4 年前。 Improv
我经常发现自己试图使用 boost/QT 信号解耦对象。实现这一点的简单方法是针对我要通信的每个具体类型,创建一个新的信号和插槽签名并连接所有相关对象。这导致了访问者模式,理想情况下我想发出一个访问者
我正在 https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html 上阅读有关 lambda 的内容 在方法
public List getInts() { List xs = new ArrayList(); xs.add(1); // return Collections.unmo
我是一名优秀的程序员,十分优秀!