基于列名计算并获取名称作为计算的一部分

2024-05-19 22:10:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要基于列名计算一个差异,并使用部分列名作为计算的一部分。你知道吗

Data frame

因此,当前促销值的列为空。我需要计算第一行的get2for30为(X-30),第二列的GET2FOR31为(X-31),并在相应的“单元格”中显示值 我想知道有没有办法用熊猫来做。你知道吗

更新-我遇到的另一个问题是Get2forX的列增加到90,所以最后一列是get2for90。我想知道是否有类似函数的东西可以应用于所有这些类型的列。(不写90道代码)


Tags: 函数代码类型差异办法get2for31get2for30get2for90
2条回答

像这样简单的事情行吗?你知道吗

df['GET2FOR30'] = df['Prices'] - 30
df['GET2FOR31'] = df['Prices'] - 31
df['GET2FOR32'] = df['Prices'] - 32

对于一般N列:

for col in [i for i in df.columns if 'GET2FOR' in i]:
    num = col[col.rindex('FOR')+3:]
    df[col] = df['Prices'] - int(num)

你可以简单的做本文件:你知道吗

df['GET2FOR30'] = df.Prices - 30
df['GET2FOR31'] = df.Prices - 31
... 

或者对于大量的列:-你知道吗

cols = df.columns
initial = 30
for i, j in enumerate(cols[2:]):
    if 'GET2FOR'in j:
        df[j] = df.Prices - (i + initial)

相关问题 更多 >