大Pandas堆叠数据帧重塑

2024-10-06 07:08:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用concat、append或merge来堆叠两个3列数据帧。结果是一个5列的数据帧,其中原始列的位置顺序不同。以下是我尝试过的一些方法:

dfTrain = pd.read_csv("agr_hi_train.csv")
dfTrain2 = pd.read_csv("english/agr_en_train.csv")
dfTrain2.reset_index()
frames = [dfTrain, dfTrain2]
test = dfTrain2.append(dfTrain, ignore_index=True)
test2 = dfTrain2.append(dfTrain)
test3 = pd.concat(frames, axis=0, ignore_index=True)
test4 = pd.merge(dfTrain,dfTrain2, right_index=True, left_index=True)

结果如下:

print(dfTrain.shape)
print(dfTrain2.shape)
print(test.shape)
print(test2.shape)
print(test3.shape)
print(test4.shape)

输出为:

(20198年5月) (20198, 5) (11998, 6) (8200, 6) (8200, 3) (11998年3月)

我希望结果是:

(20198,3)#即最后两个堆叠在一起。 你知道我为什么要增加专栏吗


Tags: csv数据truereadindextrainmergepd
1条回答
网友
1楼 · 发布于 2024-10-06 07:08:15

如果您有不同的列名,那么您的append将分隔这些列。例如:

dfTrain = pd.DataFrame(np.random.rand(8200, 3), columns=['A', 'B', 'C'])
dfTrain2 = pd.DataFrame(np.random.rand(11998, 3), columns=['D', 'E', 'F'])
test = dfTrain.append(dfTrain2)
print(test)

具有输出:

          A         B         C         D         E         F
0      0.617294  0.507264  0.330792       NaN       NaN       NaN
1      0.439806  0.355340  0.757864       NaN       NaN       NaN
2      0.740674  0.332794  0.530613       NaN       NaN       NaN
...
20195       NaN       NaN       NaN  0.295392  0.621741  0.255251
20196       NaN       NaN       NaN  0.096586  0.841174  0.392839
20197       NaN       NaN       NaN  0.071756  0.998280  0.451681

如果重命名两个dataframes中的列以匹配,那么它将对齐

dfTrain2.columns = ['A','B','C']
test2 = dfTrain.append(dfTrain2)
print(test2)

          A         B         C
0      0.545936  0.103332  0.939721
1      0.258807  0.274423  0.262293
2      0.374780  0.458810  0.955040
...
[20198 rows x 3 columns]

相关问题 更多 >