简体   繁体   中英

Slice pandas dataframe columns with an array?

This question refers to the previous post :

Where I have a dataframe and an array of values on which I want to interpolate:

df_new = pd.DataFrame(np.random.randn(5,7), columns=[402.3, 407.2, 412.3, 415.8, 419.9, 423.5, 428.3])
wl     = np.array([400.0, 408.2, 412.5, 417.2, 420.5, 423.3, 425.0])

The additional question I want to ask is HOW to slice the new dataframe:

df_int = df_new.reindex(columns=df_new.columns.union(wl)).interpolate(axis=1, limit_direction='both')

So it would contain ONLY the columns from the array wl ?

Note that the real dataset I'm using contains 480 columns, so I need something done automatically and not just assign separate values of each column.

I haven't found any example of such slicing in Stack Overflow, but perhaps I'm missing something

IIUC, you could simply do column filtering like this.

df_int[wl]

Output:

      400.0     408.2     412.5     417.2     420.5     423.3     425.0
0  0.293797  0.383745  0.424941  0.707308  0.793880 -0.233975  0.175342
1  1.306332 -0.872758 -0.301987 -0.683450 -0.534648  0.001957  0.940651
2 -0.477284 -0.076156 -0.268190  0.370769  0.434909 -0.235272  0.285097
3 -1.317292 -0.588243 -0.036146  1.169727  0.665479  0.831551  0.839762
4 -0.075600  0.166476  0.318865  0.128501 -1.167822 -1.533821 -0.795002

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