Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 598
st19297 Avatar asked Jul 22 '18 22:07

st19297


People also ask

How do you attach one DataFrame to another?

We can use the concat function in pandas to append either columns or rows from one DataFrame to another. Let's grab two subsets of our data to see how this works. When we concatenate DataFrames, we need to specify the axis. axis=0 tells pandas to stack the second DataFrame UNDER the first one.

Is pandas the same as R?

Pandas can be classified as a tool in the "Data Science Tools" category, while R is grouped under "Languages". "Easy data frame management" is the top reason why over 16 developers like Pandas, while over 58 developers mention "Data analysis " as the leading cause for choosing R.

Is pandas an R package?

The PANDA R package (Preferential Attachment based common Neighbor Distribution derived Associations) was designed to perform the following tasks: (1) identify significantly functionally associated protein pairs, (2) predict GO and KEGG terms for proteins, (3) make a cluster of proteins based on the significant protein ...

Is pandas similar to Dplyr?

Both Pandas and dplyr can connect to virtually any data source, and read from any file format. That's why we won't spend any time exploring connection options but will use a build-in dataset instead. There's no winner in this Pandas vs. dplyr comparison, as both libraries are near identical with the syntax.


1 Answers

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)
like image 88
jack6e Avatar answered Nov 05 '22 14:11

jack6e