st19297
st19297

Reputation: 629

Equivalent of R's "attach"ing a dataframe in Python?

I saw a similar question on OS but that one is different as it relates to functions and not dateframes.

Imagine we have a dataframe df with a column x. In R, if you "attach" df, then you can directly use x for example in print(x), without having to reference df as in print(df['x']). Is there any equivalent in Python?

Upvotes: 7

Views: 1662

Answers (2)

jack6e
jack6e

Reputation: 1522

First, the caveat that you should not do this. That said, you can set global variables via a loop across the columns:

df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7,8,9]})

for col in df.columns:
    globals()[col] = df[col]

>>> a
0    1
1    2
3    3

If you wanted it to be something you use regularly, perhaps you write a function (again, I strongly discourage this):

def attach(df):
    for col in df.columns:
        globals()[col] = df[col]

df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7,8,9]})
attach(df)

Upvotes: 6

ZJS
ZJS

Reputation: 4051

This sounds like aliasing

x = df.x  #alias x as df.x
df.x = 10 #change df.x

print(x) #prints out series df.x, which is now all 10s

Upvotes: 0

Related Questions