![](/img/trans.png)
[英]How do I copy a slice of a matrix and paste it to the end of the same matrix in Python?
[英]In Python, given that there is a matrix, how do I print a slice of it?
让我首先通过下面的代码片段概述当前问题的整体背景。
import pandas as pd
df = pd.read_csv("abc.csv")
df.as_matrix
输出所需的矩阵[100行x 785列]。
我在输出(使用print())上述矩阵的行时遇到困难。
我尝试了以下方法,但没有成功:
print(df[0])
print(df[:, 0])
要获得行索引等于A
的特定行:
df.iloc[A, :785]
通常,您可以使用df.iloc
通过df.iloc
从熊猫数据df.iloc
进行切片。 例如,要对多达100个行和多达785个列进行切片,可以执行以下操作:
import pandas as pd
df = pd.read_csv("abc.csv")
df = df.iloc[:100, :785]
df.as_matrix()
如果要在转换为矩阵后对第一行进行切片,请使用列表列表,因此可以执行以下操作:
print(df.as_matrix()[1,:])
这是一个工作示例:
from StringIO import StringIO
import pandas as pd
st = """
col1|col2|col3
1|2|3
4|5|6
7|8|9
"""
pd.read_csv(StringIO(st), sep="|")
df = pd.read_csv(StringIO(st), sep="|")
print("print first row from a matrix")
print(df.as_matrix()[0,:])
print("print one column")
print(df.iloc[:2,1])
print("print a slice")
print(df.iloc[:2,:])
print("print one row")
print(df.iloc[1,:])
我认为您缺少括号:
df.as_matrix()[0]
或者您可以使用:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.head.html
.head(n = 5)返回前n行
df.head(1).as_matrix()
as_matrix()
的返回值是数组数组。 所以下面的代码应该工作:
import pandas as pd
df = pd.read_csv("abc.csv")
matrix = df.as_matrix()
print(matrix[0]) # out put first row.
print(matrix[3:5] # output from 3 row up to 4 row.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.