【问题标题】:PANDAS Index specific columns corresponds to strings in a listPANDAS 索引特定列对应于列表中的字符串
【发布时间】:2021-08-23 20:06:34
【问题描述】:

我有一个 Pandas 数据框,它有几列和一个列表。如果要逐个索引与列表中的元素相同的列(例如,首先是“apple”列,然后是“grape”列),我该如何实现呢? 如果我使用像 fruits[list[0]] 这样的代码,它就不起作用,只有 fruits['apple'] 起作用。

columns = ['apple', 'mango', 'pear','grape','number']
fruits = pd.read_csv('fruit', names=columns)
list = ['apple','grape']

【问题讨论】:

标签: python pandas list


【解决方案1】:

loc 方法允许您根据数据框的任何维度进行过滤。在您的情况下,您希望根据列名进行选择,这是第二个维度。 ':' 字符表示取该维度的所有值。

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html

试试:

columns = ['apple', 'mango', 'pear','grape','number']
fruits = pd.read_csv('fruit', names=columns)
list_fruits = ['apple','grape']

for fruitname in list_fruits:
    column = list_fruits.loc[:, fruitname]

【讨论】:

    猜你喜欢
    • 2017-03-13
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2015-07-01
    • 2017-07-22
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多