【发布时间】: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