【问题标题】:Retrieving columns from data frames which are dict items in python从数据框中检索列,这些列是 python 中的 dict 项
【发布时间】:2018-09-30 06:54:56
【问题描述】:

我需要创建能够读取多个 csv 文件的代码,在文件中查找常用标题列,并将它们提取到一个数组中。我正在使用作为数据帧导入的 .csv 文件填充 python 字典,以便能够在 for 循环中调用它们。但是,我真的不知道从 dict 的每个项目中提取列的 for 循环会是什么样子。到目前为止,这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

r= int(input('How many files do you want to plot?: '))
l= range(r) 
d={}
for i in l:
    inp= str(input('Type name of file #'+str(i+1)+': '))
    d[i]= pd.read_csv(inp, sep=',') #fills dict with dataframes

print(d) ##prints dict to visually check for errors

然后,我需要命名我需要提取的列:

freq= input('Which frequency would you like to plot at?: ') ##The desired shared column (labeled by a common string) among the dataframes

在这之后,我被困住了。我只能考虑创建一个 for 循环,该循环遍历每个 dict 项,“扫描”第一行以找到标题字符串,然后获取该列,但我不知道如何编写代码。有什么建议吗???

【问题讨论】:

    标签: python dictionary for-loop dataframe


    【解决方案1】:

    给定一个数据帧字典d,您可以从每个数据帧中提取一列(或pd.Series),如下所示:

    freq = input('Which frequency would you like to plot at?: ')
    series = {k: v[freq] for k, v in d.items()}
    

    这将创建一个名为freq 的列字典。您接下来需要的操作在您的问题中并不清楚。您可能需要将它们连接起来,或者为您想要的输出执行一些计算。

    【讨论】:

      猜你喜欢
      • 2022-10-07
      • 1970-01-01
      • 2020-07-04
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      相关资源
      最近更新 更多