[英]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.