简体   繁体   中英

Selecting columns - dataframes, pandas

How do you go about selecting a column in a Pandas Dataframe, where the column name depends on a value, which we have located in another dataframe ? For example, if [1,2,3..] are column names of dataframe 1 and [1,2,3..] are values of different cells in dataframe 2. How do you select a column in dataframe 1, by matching the column name with cell value in dataframe 2.

df1 = pd.DataFrame([list('abc')], [0], [1, 2, 3])
df2 = pd.DataFrame(dict(A=[2, 3, 1]))

df1

   1  2  3
0  a  b  c

df2

   A
0  2
1  3
2  1

df1[df2.A]

   2  3  1
0  b  c  a

response to comment

df1.loc[0, df2.loc[0, 'A']]

'b'

df1.at[0, df2.at[0, 'A']]

'b'

df1.get_value(0, df2.get_value(0, 'A'))

'b'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM