在 for 循环中使用变量作为数据框列名称

Dom*_*nic 4 python loops for-loop series pandas

我尝试使用 for 循环迭代列名称列表,并在每次迭代时根据字符串前缀和原始列名称(存储在列表中)创建一个新列。问题是数据框认为变量是框架中的一系列

cols_to_transform = ['Price','Km_From_CBD','Local_Median_Price', 'AreaSize']

for x in cols_to_transform:
    df.x #This is where the problem
    df[x] = df[x>1]
    newcolname = ('T1_Pre_'+ x)
    df.newcolname = df.x + 1 #and same problem here 
Run Code Online (Sandbox Code Playgroud)

(DataFrame'对象没有属性'x')

(DataFrame'对象没有属性'newcolname')

理想情况下,我会有一个“全局变量”或参数来覆盖预期的 pandas 对象,并将变量的内容作为列名而不是变量本身。

我无法使用 pandas apply,因为除了创建列之外,我还需要创建一系列显示转换变化的子图。

我知道我可以将整行代码转换为字符串,然后使用 exec,但我真的已经厌倦了这样做,因为这感觉像是一个廉价的解决方案。

提前致谢!这也是我的第一个问题,请放轻松:)

Ern*_*ran 5

试试这个代码:

cols_to_transform = ['Price','Km_From_CBD','Local_Median_Price', 'AreaSize']

for x in cols_to_transform:
    df[x]

    newcolname = ('T1_Pre_'+ x)
    df.newcolname = df[x] + 1 
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

7378 次

最近记录:

7 年,5 月 前