python - 在 pandas dataframe 数组中加载乘法 csv,并以索引作为文件名

标签 python pandas dataframe

我已经尝试过这个:

>>> df = [pd.read_csv(x,header=None,names=["L1","L2","cache","cached","result"]) for x in iglob(os.path.join("test","**","*.csv"), recursive=True)]
>>> df
[   L1  L2  cache  cached  result
0   0   0      0       0       0
1   1   2      3       4       5
2   1   1      1       1       1
3   2   2      2       2       2
4   4   4      4       4       4,    L1  L2  cache  cached  result
0   1   2      3       4       5
1   1   2      3       4       5
2   3   4      5       6       7
3   2   1      3       2       4]

文件夹结构为:

test
|
|_______ wait
         |
         |______ 0.2322.csv
         |______ 1.234.csv

这两个文件包含:
0.2322.csv

0,0,0,0,0
1,2,3,4,5
1,1,1,1,1
2,2,2,2,2
4,4,4,4,4

1.234.csv

1,2,3,4,5
1,2,3,4,5
3,4,5,6,7
2,1,3,2,4

当我尝试从 df 数组访问数据帧时,我必须使用索引值 0,1 来调用它,即 df[0 ] 和 df[1]

但我想调用相应文件的数据帧,其中文件名作为索引 df["0.2322"]df["1.234"]。但我不知道这怎么可能。请让我知道我可以做些什么来实现我的期望。

最佳答案

我认为您需要使用不带扩展名的解析文件名进行字典理解:

import os

#https://stackoverflow.com/a/678242
df = {os.path.splitext(x)[0]: pd.read_csv(x,header=None,names=["L1","L2","cache","cached","result"]) for x in iglob(os.path.join("test","**","*.csv"), recursive=True)}

编辑:

#https://stackoverflow.com/a/37760212
df = {os.path.splitext(os.path.basename(x))[0]: pd.read_csv(x,header=None,names=["L1","L2","cache","cached","result"]) for x in iglob(os.path.join("test","**","*.csv"), recursive=True)}

关于python - 在 pandas dataframe 数组中加载乘法 csv,并以索引作为文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56373334/

相关文章:

python - 使用 Selenium 打开 Splinter 浏览器

python - 在Python中,在没有字符串的情况下,努力将数字转换为基数64

Pandas.Index.isin() 在处理大数据集时失败

python - 无法解析位置 0 处的字符串问题

python - 按特定列对行(组内)的 Pandas df 子集进行排序

python - 使用 python 创建正确的 JSON 字符串

javascript - 如何在 Django Views 中获取静态 url

python - Pandas:将描述性 Dict() 附加到分层索引(即 CountryCode 和 CountryName)

rapply 到 R 中数据框的嵌套列表

python-3.x - 处理 pyspark 数据框中的空值