在数据框中追加行?

时间:2018-10-13 07:58:04

标签: python pandas

这是我的代码:

ping

我想在testY中的每一行都出错,我做到了:

testy = pd.read_csv(file, parse_dates=True, index_col='Date', dayfirst=True)
# testy's shape is (6, 4), so 6 rows and 4 columns
basey = testy.mean(0)
# basey is the average of each column of testy, and the shape is (1, 4)

但是,由于testy是(6,4)而basey.T是(1,4),看来我没有得到正确的结果。正确的方法是什么?

2 个答案:

答案 0 :(得分:0)

numpy中,数学运算通常更容易完成。您可以使用df.values提取数据帧numpy数组。因此,在这种情况下,如果您的框架尺寸正确,则可以执行以下操作:

error_y = test_y.values - base_y.T

答案 1 :(得分:0)

您可以将数据帧转换为numpy数组,执行操作(在numpy中相对容易执行),然后再转换回去。

testy =  pd.read_csv(file, parse_dates=True, index_col='Date', dayfirst=True)
# Get the numpy array for testy, less the indices
arr = testy.reset_index().values[:, 1:]
mean = np.mean(arr, axis = 0)
# Convert back to pandas, set the indices from testy
errory = pd.DataFrame(arr - mean, index = testy.index.values)
# Set the column names in errory same as testy
errory.columns = testy.columns