【问题标题】:How do I successively decrease the number of times a value appears in a column using python?如何使用python连续减少值出现在列中的次数?
【发布时间】:2018-07-03 00:12:06
【问题描述】:

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

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

我希望输出是:

  1. 你好
  2. 你好
  3. 你好
  4. 不错
  5. 工作

代码:

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. 工作

如何获得我想要的输出?如果 x = 50,我应该如何更改代码?无法编写更多 if 语句。请帮忙

【问题讨论】:

  • 如果这是一个格式问题,也许只需在必要的地方添加一个新行\n,例如(testfile.iloc[i,0] + '\n')*n ?

标签: python-3.x pandas append


【解决方案1】:

通过使用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

【讨论】:

  • 这真是天才!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
  • 1970-01-01
  • 2021-02-22
  • 2016-08-23
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
相关资源
最近更新 更多