我有一个熊猫DataFrame 4列,我想创建一个新的DataFrame,只有三个列。这个问题类似于:从数据帧中提取特定的列,但对于熊猫而不是r。下面的代码不起作用,会引发错误,当然不是熊猫的方式。

import pandas as pd
old = pd.DataFrame({'A' : [4,5], 'B' : [10,20], 'C' : [100,50], 'D' : [-30,-50]})
new = pd.DataFrame(zip(old.A, old.C, old.D)) # raises TypeError: data argument can't be an iterator 

熊猫式的做法是什么?


当前回答

据我所知,在使用过滤器函数时,不一定需要指定轴。

new = old.filter(['A','B','D'])

返回相同的数据框架

new = old.filter(['A','B','D'], axis=1)

其他回答

据我所知,在使用过滤器函数时,不一定需要指定轴。

new = old.filter(['A','B','D'])

返回相同的数据框架

new = old.filter(['A','B','D'], axis=1)

按索引排列的列:

# selected column index: 1, 6, 7
new = old.iloc[: , [1, 6, 7]].copy() 

泛函形式

def select_columns(data_frame, column_names):
    new_frame = data_frame.loc[:, column_names]
    return new_frame

针对你上面的问题

selected_columns = ['A', 'C', 'D']
new = select_columns(old, selected_columns)

如果你想有一个新的数据帧,那么:

import pandas as pd
old = pd.DataFrame({'A' : [4,5], 'B' : [10,20], 'C' : [100,50], 'D' : [-30,-50]})
new=  old[['A', 'C', 'D']]

作为替代:

new = pd.DataFrame().assign(A=old['A'], C=old['C'], D=old['D'])