我已经尝试过这个:
>>> 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/