【问题标题】:How can I get a previous value with some condition in a dataframe in pandas如何在熊猫的数据框中获得具有某些条件的先前值
【发布时间】:2021-08-04 12:44:33
【问题描述】:

您好,如果此值包含“-”,我正在尝试获取特定列中的前一个值:

这是我的代码:

count=-1
for i, row in df1.iterrows():
    count=count + 1
    if row["SUBCAPITULO"]== " "and count>0 and "-" in df1.loc[count-1:"SUBCAPITULO"]:
        row["SUBCAPITULO"]= df1.loc[count-1:"SUBCAPITULO"]

【问题讨论】:

  • 你能用df1 的样本更新你的帖子吗? df1.head() 的输出应该足够了。
  • pandas.ffilll ?
  • @woblob。这里不可能立即进行,因为还有第二个条件。可能使用 shift 更合适。

标签: python pandas loops


【解决方案1】:

使用shift:

示例:

>>> df
  SUBCAPITULO
0       dash-
1
2      comma,
3
4        dot.
df.loc[(df['SUBCAPITULO'] == ' ') &
       (df['SUBCAPITULO'].shift().str.contains('-'))] = df['SUBCAPITULO'].shift()
>>> df
  SUBCAPITULO
0       dash-
1       dash-
2      comma,
3
4        dot.

【讨论】:

  • 我认为 OP 想要在多行中填充 dash- 值。
  • @Corralien 嗨,我尝试了您的代码,但无法正常工作:ValueError: Must have equal len keys and value when setting with an iterable
  • 请解释原因?
  • @Corralien 看,如果前一行有“-”,我想替换空格
【解决方案2】:

所需的输出尚未发布,请求不明确。

考虑到这些 cmets:

  • 如果该值包含破折号,则尝试获取特定列中的前一行值
  • 我认为 OP 想要在多行上填充破折号值

也许这会有所帮助...

import pandas as pd

df = pd.read_csv('test.csv')

print(df, '\n\n')

'''
Shows:

  Other_data       SUBCAPITULO
0       qwer               NaN
1       vfds               NaN
2       sdfg  1.01 – TORRE – 1
3       hfgt               NaN
4       jkiu          capitulo
5       bvcd  2.01 – TORRE – 1
6       grnc               NaN
7       sdfg          capitulo
8       poij               NaN
9       fghg  2.01 – TORRE – 1 

'''

for i in reversed(df.index):
    if i >= 1:
        if '–' in str(df.loc[i, 'SUBCAPITULO']):
            if str(df.loc[i-1, 'SUBCAPITULO']) == 'nan': 
                df.loc[i-1, 'SUBCAPITULO'] = df.loc[i, 'SUBCAPITULO']

print(df)


'''
Shows:

  Other_data       SUBCAPITULO
0       qwer  1.01 – TORRE – 1
1       vfds  1.01 – TORRE – 1
2       sdfg  1.01 – TORRE – 1
3       hfgt               NaN
4       jkiu          capitulo
5       bvcd  2.01 – TORRE – 1
6       grnc               NaN
7       sdfg          capitulo
8       poij  2.01 – TORRE – 1
9       fghg  2.01 – TORRE – 1

'''

print('\n')

【讨论】:

    【解决方案3】:
    df1.reset_index(drop=True, inplace=True)
    for i in range(1, len(df1)):
      if df1.loc[i, 'SUBCAPITULO'] == " " and "-" in df1.loc[i-1, 'SUBCAPITULO']:
        df1.loc[i, 'SUBCAPITULO']=df1.loc[i-1, 'SUBCAPITULO']
    
    df1.dropna(inplace=True)
    

    问题是我必须在循环之前重置索引。

    enter image description here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 2023-03-14
      • 1970-01-01
      • 2018-11-22
      • 2017-04-05
      • 2020-10-03
      • 2016-02-17
      相关资源
      最近更新 更多