假设我有一个名为 x 的列表
x = ['Sales', 'Total', 'Quantity']
我有一个 excel 数据框,其中包含名为“员工”、“年龄”、“性别”、“销售额”、“数量”和“总计”的列。 如何让 Pandas 只选择与列表中名称相同的数据框列?
答案 0 :(得分:2)
就去做:
x = ['Sales', 'Total', 'Quantity']
df = df[x]
由于 x
已经是一个列列表,所以在 single-brackets
中使用它来对数据框进行子集化。
OR 使用 Index.intersection
:
df = df[df.columns.intersection(x)]
答案 1 :(得分:1)
只需执行以下操作即可选择列:
df = df[x]
答案 2 :(得分:1)
x = ['Sales', 'Total', 'Quantity']
df.drop(columns=[col for col in df if col not in x], inplace=True)