Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何读取数据帧中的数组?_Python_Pandas - Fatal编程技术网

Python 如何读取数据帧中的数组?

Python 如何读取数据帧中的数组?,python,pandas,Python,Pandas,我有一个tsv文件,其中包含一个数组,该数组已使用read\u csv()读取 数组的数据类型显示为dtype:object。如何读取它并将其作为数组访问 例如: df= id values 1 [0,1,0,3,5] 2 [0,0,2,3,4] 3 [1,1,0,2,3] 4 [2,4,0,3,5] 5 [3,5,0,3,5] 目前,我正在将其解包如下: for index,row in df.iterrows(): string = row['c

我有一个tsv文件,其中包含一个数组,该数组已使用
read\u csv()
读取

数组的数据类型显示为
dtype:object
。如何读取它并将其作为数组访问

例如:

df=

id   values
1    [0,1,0,3,5]
2    [0,0,2,3,4]
3    [1,1,0,2,3]
4    [2,4,0,3,5]
5    [3,5,0,3,5]
目前,我正在将其解包如下:

for index,row in df.iterrows():
    string = row['col2']
    string=string.replace('[',"")
    string=string.replace(']',"")
    v1,v2,v3,v4,v5=string.split(",")
    v1=int(v1)
    v2=int(v2)
    v3=int(v3)
    v4=int(v4)
    v5=int(v5)
id   values
1    [0,1,0,3,5]
2    [0,0,2,3,4]
3    [1,1,0,2,3]
4    [2,4,0,3,5]
5    [3,5,0,3,5]
除此之外还有其他选择吗

之所以要这样做,是因为我想在数据帧中创建另一列,取所有值的平均值

添加其他详细信息:col2

我的tsv文件如下所示:

for index,row in df.iterrows():
    string = row['col2']
    string=string.replace('[',"")
    string=string.replace(']',"")
    v1,v2,v3,v4,v5=string.split(",")
    v1=int(v1)
    v2=int(v2)
    v3=int(v3)
    v4=int(v4)
    v5=int(v5)
id   values
1    [0,1,0,3,5]
2    [0,0,2,3,4]
3    [1,1,0,2,3]
4    [2,4,0,3,5]
5    [3,5,0,3,5]
我正在阅读tsv文件,如下所示:
df=pd.read\u csv('tsv\u file\u name.tsv',sep='\t',header=0)
您可以使用
json
简化解析:

import json
df['col2'] = df.col2.apply(lambda t: json.loads(t))
编辑:根据您的评论,获得平均值很容易:

# using numpy
df['col2_mean'] df.col2.apply(lambda t: np.array(t).mean())
# by hand
df['col2_mean'] df.col2.apply(lambda t: sum(t)/len(t))


可能重复的CSV文件您能举一个CSV文件的例子吗?您使用什么确切的代码将其加载为数据帧?我的印象是,通过设置分隔符(可能还有一点预处理),您可以以更干净的方式完成这项工作。好的,我会添加它。有没有进一步的方法可以让我们获得元素的平均值?它很有效,感谢您展示了lambda的使用,我甚至能够应用所需的操作。我想要一个加权平均值,我能够应用权重并做到这一点。谢谢。虽然这个代码片段可以解决这个问题,但它确实有助于提高文章的质量。请记住,您将在将来回答读者的问题,这些人可能不知道您的代码建议的原因。