Pandas 将一张桌子分解成几行
将python中的表或矩阵分解为包含列及其值信息的行的最佳解决方案性能是什么 假设我们加载了一张熊猫表,如下所示:Pandas 将一张桌子分解成几行,pandas,Pandas,将python中的表或矩阵分解为包含列及其值信息的行的最佳解决方案性能是什么 假设我们加载了一张熊猫表,如下所示: Date A B t1 1 2 t2 3 4 Date A B C t1 1 5 9 t1 2 6 10 t2 3 7 11 t2 4 8 12 我要分解表格,使其成为一系列4行,如下所示: t1-A-1 t1-B-2 t2-A-3 t2-C-4 当原始表中可能有几十列和数百行时,性
Date A B
t1 1 2
t2 3 4
Date A B C
t1 1 5 9
t1 2 6 10
t2 3 7 11
t2 4 8 12
我要分解表格,使其成为一系列4行,如下所示:
t1-A-1
t1-B-2
t2-A-3
t2-C-4
当原始表中可能有几十列和数百行时,性能是关键
那么以下内容呢:
Date A B
t1 1 2
t2 3 4
Date A B C
t1 1 5 9
t1 2 6 10
t2 3 7 11
t2 4 8 12
输出系列为:
Date code
t1 "str1"1"str2"B"str2"5
t1 "str1"2"str2"B"str2"6
t2 "str1"3"str2"B"str2"7
t2 "str1"4"str2"B"str2"8
.. ..
t2 "str1"4"str2"C"str2"12
我感谢你的帮助
df.set_index('Date').stack().reset_index().apply(lambda x: '-'.join(x.astype(str)), axis=1)
输出:
0 t1-A-1
1 t1-B-2
2 t2-A-3
3 t2-B-4
dtype: object
输出:
0 t1-A-1
1 t1-B-2
2 t2-A-3
3 t2-B-4
dtype: object
如果性能是关键。。。使用numpy 时机 小数据 大数据
如果性能是关键。。。使用numpy 时机 小数据 大数据
B5和C3发生了什么?B5和C3发生了什么?太棒了!谢谢,太好了!谢谢
from string import ascii_letters
np.random.seed([3,1415])
df = pd.DataFrame(
np.random.randint(10, size=(1000, 52)),
pd.Index(['t{:05d}'.format(i) for i in range(1000)], name='Date'),
list(ascii_letters)
).reset_index()
10 loops, best of 3: 156 ms per loop
1 loop, best of 3: 3.75 s per loop