Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

python - Keep one column in df2 based on value in df1

Suppose I have two dataframes:

data = {'model':  ['B']}
df1 = pd.DataFrame (data, columns = ['model'])
df1

data = {'A':  ['0.55', '0.49', '0.47',],
        'B': ['0.48', '0.53', '0.54'],
        'C': ['0.50', '0.51', '0.45']}
df2 = pd.DataFrame (data, columns = ['A', 'B', 'C'])
df2

I would like df2 to keep only the column where the name is equal to the value in df1. So the output would be that df2 only has one column in the dataframe - 'B'

How would I do this?

Thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do:

import pandas as pd
data = {'model':  ['B']}
df1 = pd.DataFrame (data, columns = ['model'])
data = {'A':  ['0.55', '0.49', '0.47',],
        'B': ['0.48', '0.53', '0.54'],
        'C': ['0.50', '0.51', '0.45']}
df2 = pd.DataFrame (data, columns = ['A', 'B', 'C'])
outdf = df2[df1['model']]  # alternatively: outdf = df2[df1.model]
print(outdf)

Output:

      B
0  0.48
1  0.53
2  0.54

Explanation: we can use [] (getitem) to get certain columns from pandas.DataFrame by using iterable - in this case it is pandas.Series (column) from df1 named model.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...