【问题标题】:How to iterate through pandas columns and replace cells with information with the next row down如何遍历pandas列并将单元格替换为下一行的信息
【发布时间】:2018-07-31 16:39:12
【问题描述】:

我正在尝试遍历 pandas 数据框列,并根据下一行是否不包含“属性地址”将下一行的信息添加到上一行。例如,如果我有一列从上到下 ["Property Address", "Alternate Address", "Property Address"] 我想从 "Alternate Address" 中获取信息并将该信息添加到上面的列它(“物业地址”)。我已经仔细检查了是否没有尾随或前导空格,并且所有内容都是小写的,以便所有比较都有效。但是,我仍然收到此错误:

if i == "Property Address" and df.loc[i+1, :] != "Property Address":

TypeError: must be str, not int

有没有人知道我可以做些什么来让这行得通?我是 Python 新手,我真的迷路了。如果我应该提供更多信息以便更轻松地回答这个问题,请告诉我。谢谢

到目前为止,这是我的代码:

import pandas as pd
import time

df = pd.read_excel('BRH.xls') # Reads the Excel File and creates a 
dataframe 
# Column Headers
df = df[['street', 'state', 'zip', 'Address Type', 'mStreet', 'mState', 'mZip']]

propertyAddress = "Property Address" # iterates thru column and replaces 
the current row with info from next row down

for i in df['Address Type']:
  if i == "Property Address" and df.loc[i+1, :] != "Property Address":
      df['mStreet'] == df.loc[i + 1, 'street']
      df['mState'] == df.loc[i + 1, 'state']
      df['mZip'] = df.loc[i + 1, 'zip']

df.to_excel('BRHOut.xls')
print('operation complete in:', time.process_time(), 'ms')

【问题讨论】:

  • 您能否向我们展示您输入数据的示例 [敏感数据除外,我们只需要知道格式]?

标签: python pandas for-loop if-statement dataframe


【解决方案1】:

您可以使用pd.Series.shift 构造一个合适的掩码。

这是一些未经测试的伪代码:

m1 = df['AddressType'].shift() == 'Property Address'
m2 = df['AddressType'] != 'Property Address'
mask = m1 & m2

for col in ['Street', 'State', 'Zip']:
    df.loc[mask, 'm'+col] = df.loc[mask, col.lower()].shift(-1)

【讨论】:

    【解决方案2】:

    您的TypeError 正在发生,因为i 是一个字符串。当您调用df.loc[i+1, :] 时,您正在尝试执行"Property Address" + 1 之类的操作。一旦你解决了这个问题,你的 for 循环体中仍然会有一些索引问题。

    @jpp 给出了一个非常简洁的答案,但我相信它会从预期的目的地提取信息并将其写入预期的来源。换句话说,“物业地址”和“备用地址”的角色是相反的。我相信这会产生正确的结果:

    设置

    import pandas as pd
    
    df = pd.DataFrame(data={
            'street': [
                '123 Main Street',
                '1600 Pennsylvania Ave',
                '567 Fake Ave',
                '1 University Ave'
            ],
            'state': ['CA', 'DC', 'DC', 'CA'],
            'zip': ['95126', '20500', '20500', '94301'],
            'Address Type': [
                'Property Address',
                'Alternate Address',
                'Property Address',
                'Alternate Address'
            ],
            'mStreet': [None, None, None, None],
            'mState': [None, None, None, None],
            'mZip': [None, None, None, None],
        },
        columns=[
            'street',
            'state',
            'zip',
            'Address Type',
            'mStreet',
            'mState',
            'mZip'
        ])
    
    # Create a new dataframe with all address attributes shifted UP one row
    next_address_attributes = df[['Address Type', 'street', 'state', 'zip']].shift(-1)
    
    # Create a series to indicate whether information should be drawn from next row
    # All the decision-making is right here
    get_attributes_from_next_address = ((df['Address Type'] == 'Property Address')
        & (next_address_attributes['Address Type'] != 'Property Address'))
    

    使用 For 循环

    for i, getting_attributes_is_necessary in get_attributes_from_next_address.iteritems():
        if getting_attributes_is_necessary:
            df.at[i, 'mStreet'] = next_address_attributes.at[i, 'street']
            df.at[i, 'mState'] = next_address_attributes.at[i, 'state']
            df.at[i, 'mZip'] = next_address_attributes.at[i, 'zip']
    

    无环

    df.loc[get_attributes_from_next_address, 'mStreet'] = next_address_attributes.loc[get_attributes_from_next_address, 'street']
    df.loc[get_attributes_from_next_address, 'mState'] = next_address_attributes.loc[get_attributes_from_next_address, 'state']
    df.loc[get_attributes_from_next_address, 'mZip'] = next_address_attributes.loc[get_attributes_from_next_address, 'zip']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多