以前,在R中,我使用sub和paste将字符串和数字连接在一起。
我发现Python有点难。下面是Python中的示例代码import pandas as pd
from numpy.random import rand
random.seed(1)
testtt = round(pd.DataFrame(rand(5,4)),3)
testtt.iloc[1,1]
print(testtt)
# 0 1 2 3
# 0 0.417 0.720 0.000 0.302
# 1 0.147 0.092 0.186 0.346
# 2 0.397 0.539 0.419 0.685
# 3 0.204 0.878 0.027 0.670
# 4 0.417 0.559 0.140 0.198
for i in range(testtt.shape[1]):
for j in range(testtt.shape[0]):
testtt.iloc[j,i] = str(i) + '_' + str(testtt.iloc[j,i],)
print(testtt)
# 0 1 2 3
# 0 0_0.417 1_0.72 2_0.0 3_0.302
# 1 0_0.147 1_0.092 2_0.186 3_0.346
# 2 0_0.397 1_0.539 2_0.419 3_0.685
# 3 0_0.204 1_0.878 2_0.027 3_0.67
# 4 0_0.417 1_0.559 2_0.14 3_0.198
实际上,我期待着在它下面的数字上添加列索引。如您所见,第一列的“0”被添加到该列下的所有元素中,对于第二列,“1”被添加,依此类推。在
我认为for loops并不是最好的方法,因为我的实际数据是一个由90000*20个元素组成的矩阵,运行时间太长。在
这是我以前在R中编写的代码,它的速度要快得多,因为列数是20,而且它只在列中使用了一个短循环:
^{pr2}$
我对Python很陌生。请你考虑一下。在