python - 如何根据列名、另一列中的值和索引范围替换数据框中列中的值?
问题描述
我有一个具有这些特征的数据框(索引是浮点值):
import pandas as pd
d = {'A': [1,2,3,4,5,6,7,8,9,10],
'B': [1,2,3,4,5,6,7,8,9,10],
'C': [1,2,3,4,5,6,7,8,9,10],
'D': ['one','one','one','one','one','two','two','two','two','two']}
df = pd.DataFrame(data=d)
df
A B C D
50.0 1 1 1 one
50.2 2 2 2 one
50.4 3 3 3 one
50.6 4 4 4 one
50.8 5 5 5 one
51.0 6 6 6 two
51.2 7 7 7 two
51.4 8 8 8 two
51.6 9 9 9 two
51.8 10 10 10 two
以及具有这些值的偏移量列表(它们也是浮点数):
offsets = [[0.4, 0.6, 0.8], [0.2, 0.4, 0.6]]
我需要在 A、B 和 C 列上遍历我的数据框,从 D 列中选择分类值,根据与列表中偏移量相关的索引将 A、B 和 C 列中的最后一个值替换为 nan,从而导致像这样的数据框:
A B C D
50.0 1 1 1 one
50.2 2 2 nan one
50.4 3 nan nan one
50.6 nan nan nan one
50.8 nan nan nan one
51.0 6 6 6 two
51.2 7 7 7 two
51.4 8 8 nan two
51.6 9 nan nan two
51.8 nan nan nan two
偏移量的值意味着什么值必须从下往上设置为 nan。例如:offsets[0][0]=0.4,所以对于A列当D == 'one'时,自下而上的两个值必须设置为nan(第4行和第3行,50.8-0.4 = 50.4 - 50.4不变)。对于 A,当 D == 'two' 时,偏移量[1][0]=0.2,因此必须将自下而上的一个值设置为 nan(第 9 行,51.8-0.2 = 51.6 - 51.6 不变)。Offsets[1][0]=0.6,所以对于B列当D == 'one'时,自下而上的三个值必须设置为nan(第4、3和2行,50.8-0.6 = 50.2 - 50.2不'不改变)。对于 B,当 D == 'two' 时,偏移量[1][1]=0.4,因此必须将自下而上的两个值设置为 nan(第 9 行和第 8 行,51.8-0.4 = 51.4 - 51.4 不变)。对于 C 列是相同的。
知道怎么做吗?快速评论 - 我想在数据框本身中替换这些值,而不创建新值。
解决方案
一种方法是使用apply
将每列的最后一个值设置为 NaN:
import pandas as pd
# toy data
df = pd.DataFrame(data={'A': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'B': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'C': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'D': ['one', 'one', 'one', 'one', 'one', 'two', 'two', 'two', 'two', 'two']})
offsets = [2, 3, 4]
offset_lookup = dict(zip(df.columns[:3], offsets))
def funny_shift(x, ofs=None):
"""This function shift each column by the given offset in the ofs parameter"""
for column, offset in ofs.items():
x.loc[x.index[-1 * offset:], column] = None
return x
df.loc[:, ["A", "B", "C"]] = df.groupby("D").apply(funny_shift, ofs=offset_lookup)
print(df)
输出
A B C D
0 1.0 1.0 1.0 one
1 2.0 2.0 NaN one
2 3.0 NaN NaN one
3 NaN NaN NaN one
4 NaN NaN NaN one
5 6.0 6.0 6.0 two
6 7.0 7.0 NaN two
7 8.0 NaN NaN two
8 NaN NaN NaN two
9 NaN NaN NaN two
更新
如果每个组有多个更新,您可以这样做:
offsets = [[2, 3, 4], [1, 2, 3]]
offset_lookup = (dict(zip(df.columns[:3], offset)) for offset in offsets)
def funny_shift(x, ofs=None):
"""This function shift each column by the given offset in the ofs parameter"""
current = next(ofs)
for column, offset in current.items():
x.loc[x.index[-1 * offset:], column] = None
return x
df.loc[:, ["A", "B", "C"]] = df.groupby("D").apply(funny_shift, ofs=offset_lookup)
print(df)
推荐阅读
- java - Tomcat 中的 REST API 客户端返回 ConnectionTimedOut
- php - 如何让更新表单工作的“id”?
- c# - 是否可以在不关闭计算机的情况下生成 hiberfil.sys(生成内存的完整映像)?
- java - Java 计算 1*3*5*7*...* 给用户给定的 double
- android - onSwipeCompleted view dissapiers,有空白空间和刷卡不再起作用
- qt - 在 Qt Creator 中打开一个 Qt cmake 项目总是重新运行 cmake
- json - 发布到 Microsoft Teams 连接器 Webhook 时,消息可以保留多长时间?
- r - R:如何构造一个重复的单位矩阵
- javascript - 更改事件以检查任何表单元素的更改
- python - python、arduino和无毛MIDI之间的串行通信