我有一个看起来像这样的数据帧:
statistics
0 2013-08
1 4
2 8
3 2013-09
4 7
5 13
6 2013-10
7 2
8 10
我需要它看起来像这样:
statistics X Y
0 2013-08 4 8
1 2013-09 7 13
2 2013-10 2 10
找到一种不依赖于行数的方法会很有用,因为我想在循环中使用它,并且原始行的数量可能会发生变化。但是,输出应始终具有这 3 列
您正在执行的操作不是解栈操作,而是尝试进行重塑。 你可以通过使用 numpy 的 reshape 方法来执行此操作。变量n_cols是您要查找的列数。
这里有一个例子:
df = pd.DataFrame(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], columns=['col'])
df
col
0 A
1 B
2 C
3 D
4 E
5 F
6 G
7 H
8 I
9 J
10 K
11 L
n_cols = 3
pd.DataFrame(df.values.reshape(int(len(df)/n_cols), n_cols))
0 1 2
0 A B C
1 D E F
2 G H I
3 J K L
import pandas as pd
data = pd.read_csv('data6.csv')
x=[]
y=[]
statistics= []
for i in range(0,len(data)):
if i%3==0:
statistics.append(data['statistics'][i])
elif i%3==1:
x.append(data['statistics'][i])
elif i%3 == 2:
y.append(data['statistics'][i])
data1 = pd.DataFrame({'statistics':statistics,'x':x,'y':y})
data1