如何在Python中打印Dataframe的名称并检查Dataframe中的行和列?
在Python中显示Dataframe的名称并检查Dataframe中的行和列时,我遇到了一个问题 这是我的数据帧,包括行和列如何在Python中打印Dataframe的名称并检查Dataframe中的行和列?,python,pandas,dataframe,Python,Pandas,Dataframe,在Python中显示Dataframe的名称并检查Dataframe中的行和列时,我遇到了一个问题 这是我的数据帧,包括行和列 print("x_train: ",x_train.shape) print("x_test: ",x_test.shape) print("y_train: ",y_train.shape) print("y_test: ",y_test.shape) 输出如下所示 x_train: (30, 455) x_test: (30, 114) y_train: (
print("x_train: ",x_train.shape)
print("x_test: ",x_test.shape)
print("y_train: ",y_train.shape)
print("y_test: ",y_test.shape)
输出如下所示
x_train: (30, 455)
x_test: (30, 114)
y_train: (455,)
y_test: (114,)
我编写了如下所示的代码snippt,以显示Dataframe的名称以及Dataframe的行和列。
它将元组抛出范围之外,因为y_列和y_测试没有列
def showRowsandColumns(value):
name =[x for x in globals() if globals()[x] is value][0]
if not isinstance(value, pd.DataFrame):
value = value.to_frame()
if not value.shape[0] and value.shape[1]:
value_count_row = value.shape[0] # gives number of row count
value_count_col = value.shape[1] # gives number of col count
elif value.shape[0] and not value.shape[1]:
value_count_row = value.shape[0] # gives number of row count
value_count_col = 0
elif not value.shape[0] and value.shape[1]:
value_count_row = 0 # gives number of row count
value_count_col = value.shape[1]
else:
value_count_row = value.shape[0] # gives number of row count
value_count_col = value.shape[1] # gives number of col count
print("{} : {} rows and {} columns "
.format(name,value_count_row,value_count_col))
showRowsandColumns(x_train)
showRowsandColumns(x_test)
showRowsandColumns(y_train)
showRowsandColumns(y_test)
错误是:
AttributeError: 'numpy.ndarray' object has no attribute 'to_frame'
如何修复它?如果要查找行数和列数,那么pandas.DataFrame.shape将返回一个包含行、列的元组您的方法会对y\u train和y\u test抛出错误,因为它们不是数据帧,而是实际序列。你可以从它们的形状看出来。如果您愿意,您可以进行printtypey_测试,它将显示它们是契约系列,而不是数据帧 最简单的方法之一是在将y_测试和y_序列传递给您的方法之前,将其转换为数据帧:
y_test = y_test.to_frame()
showRowsandColumns(y_test)
在您的案例中,您只对序列执行此操作y_测试,y_训练
请注意,这些已更改为DataFrme,因此您需要对其进行适当的处理
以下是一个例子:
y = df['col5']
print(y.shape)
print(type(y))
print(y.ndim)
(4,)
<class 'pandas.core.series.Series'>
1
我称你的函数为:
showRowsandColumns(y)
4 rows and 1 columns
我的问题是基于如何解决函数中的问题。我已经知道了形状函数,所以您有numpy.ndarray,而不是您在原始问题中所述的数据帧。正当
showRowsandColumns(y)
4 rows and 1 columns