我有以下格式的CSV文件:
index A B C
ind1 [1,2,3][3,4,5][6,7,8]
ind2 [1,4,3,4,8][9,1,2,1,4][3,7,3,5,9]
ind3 [2,8][1,8][1,5]
Run Code Online (Sandbox Code Playgroud)
每个单元格(例如A,ind1)都有一个列表[1,2,3]。当我将其导入数据框时:
df=pd.read_csv('filename.csv')
Run Code Online (Sandbox Code Playgroud)
我得到的格式与csv相同的数据框,但是,单个单元格中的列表作为字符串导入。
说我索引ind1列A的第一个元素
df.iloc[0]['A']给我'['而不是1
基本上,它是[1,2,3]作为一个长字符串读取而不是作为列表读取。
如何将所有单元格中的值转换为列表?
我有一个目录,其中包含更多子目录,每个子目录都有具有特定扩展名的文件。我可以使用 glob 函数获取所有文件的名称:
for name in glob.glob('*/*[a-b]*'):
print(os.path.basename(name))
Run Code Online (Sandbox Code Playgroud)
打印我在所有子目录中的文件名:
PF44_aa
PF52_aa
PF95_aa
PF38_aa
PF45_aa
PF63_aa
PF68_aa
PF39_aa
Run Code Online (Sandbox Code Playgroud)
但是,如果我将这些文件名作为参数传递以打开文件并读取内容:
for name in glob.glob('*/*[a-b]*'):
filename=os.path.basename(name)
with open('%s' %filename) as fn:
content = fn.readlines()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
File "<ipython-input-194-147f38fc2684>", line 1, in <module>
with open('%s' %filename) as fn:
FileNotFoundError: [Errno 2] No such file or directory: 'PF44_aa'
Run Code Online (Sandbox Code Playgroud)
我还尝试直接将文件名作为输入而不是%s:
for name in glob.glob('*/*[a-b]*'):
filename=os.path.basename(name)
with open(filename) as fn:
content = fn.readlines()
Run Code Online (Sandbox Code Playgroud)
但仍然遇到同样的错误:
File "<ipython-input-193-fb125b5aa813>", line 1, in <module>
with open(filename) as fn:
FileNotFoundError: [Errno …Run Code Online (Sandbox Code Playgroud) 我有一个pandas数据帧:
0 1 2 3 4
0 4.8 2.1 0 6.2 0
1 8.5 4.9 0 2.2 0
2 0 5.3 6 9.3 0
Run Code Online (Sandbox Code Playgroud)
和两个列表:ind = [ind1,ind2,ind3]和col = [col1,col2,col3,col4,col5]
我想重命名数据框索引和列,以便:
col1 col2 col3 col4 col5
ind1 4.8 2.1 0 6.2 0
ind2 8.5 4.9 0 2.2 0
ind3 0 5.3 6 9.3 0
Run Code Online (Sandbox Code Playgroud)
我尝试将列表转换为数据帧,并通过df.append(col)和df.append(ind)追加.但这不起作用(可能是因为df的索引与col和ind数据帧的索引不同)
我该怎么做呢?