如何使用python连续减少值在列中出现的次数



我有一列(TESTFILE(,它有x值(在这个例子中x = 4,它会接近50:

  1. 你好
  2. 工作
  3. 今天

我希望输出为:

  1. 你好
  2. 你好
  3. 你好
  4. 工作

法典:

out1 = []
for i in range(len(testfile)):    
    n = len(testfile) - 1
    if i ==0:
        filepath = (testfile.iloc[i,0])*n
        out1.append(filepath)       
    elif i ==1:
        filepath = (testfile.iloc[i,0])* (n-1)   
        out1.append(filepath)
    else:
        filepath = (testfile.iloc[i,0])* (n-2)
        out1.append(filepath)
    print (filepath)   

目前的输出是:

    你好
  1. 你好
  2. 古德
  3. 古德
  4. 工作

如何获得所需的输出?如果 x = 50,我应该如何更改代码?如果语句不能写入更多。请帮忙

通过使用repeat

s.repeat(s.index.values[::-1]).reset_index(drop=True)
Out[1183]: 
0    hello
1    hello
2    hello
3     good
4     good
5      job
Name: Val, dtype: object

数据输入

s
Out[1182]: 
0    hello
1     good
2      job
3    today
Name: Val, dtype: object

最新更新