How do I select columns a and b from df, and save them into a new dataframe df1? index a b c 1 2 3 4 2 3 4 5 Unsuccessful attempt: df1 = df['a':'b'] df1 = df.ix[:, 'a':'b']
To select specific columns 'a' and 'b' from a DataFrame and create a new DataFrame df1
, you can use the following code:
python
import pandas as pd
# Assuming you have a DataFrame named 'df'
data = {'a': [1, 2], 'b': [3, 4], 'c': [4, 5]}
df = pd.DataFrame(data)
# Select columns 'a' and 'b' and create a new DataFrame 'df1'
df1 = df[['a', 'b']]
print(df1)
In this example, df[['a', 'b']]
selects the columns 'a' and 'b' from the original DataFrame and creates a new DataFrame df1
containing only these columns.
The output will be:
css
a b
0 1 3
1 2 4
So, df1
contains only the columns 'a' and 'b' from the original DataFrame df
.
Comments
Post a Comment