这就是我会做的。我不建议在使用 pandas 时循环。有很多工具通常不需要。对此有些警告。你的电子表格有 NaN 我认为这实际上是 numpy np.nan 等价物。你也有空白我认为它是一个“”等价物。
import pandas as pd
import numpy as np
# dictionary of your data
companies = {
'Comp ID': ['C1', '', np.nan, 'C2', '', np.nan, 'C3',np.nan],
'Address': ['10 foo', 'Suite A','foo city', '11 spam','STE 100','spam town', '12 ham', 'Myhammy'],
'phone': ['888-321-4567', '', np.nan, '888-321-4567', '', np.nan, '888-321-4567',np.nan],
'Type': ['W_sale', '', np.nan, 'W_sale', '', np.nan, 'W_sale',np.nan],
}
# make the frames needed.
df = pd.DataFrame( companies)
df1 = pd.DataFrame() # blank frame for suite and town columns
# Edit here to TEST the data types
for r in range(0, 5):
v = df['Comp ID'].values[r]
print(f'this "{v}" is a ', type(v))
# So this will tell us the data types so we can construct our where(). Back to prior answer....
# Need a where clause it is similar to a if() statement in excel
df1['Suite'] = np.where( df['Comp ID']=='', df['Address'], np.nan)
df1['City/State'] = np.where( df['Comp ID'].isna(), df['Address'], np.nan)
# copy values to rows above
df1 = df1[['Suite','City/State']].backfill()
# joint the frames together on index
df = df.join(df1)
df.drop_duplicates(subset=['City/State'], keep='first', inplace=True)
# set the column order to what you want
df = df[['Comp ID', 'Type', 'Address', 'Suite', 'City/State', 'phone' ]]
输出
| Comp ID |
Type |
Address |
Suite |
City/State |
phone |
| C1 |
W_sale |
10 foo |
Suite A |
foo city |
888-321-4567 |
| C2 |
W_sale |
11 spam |
STE 100 |
spam town |
888-321-4567 |
| C3 |
W_sale |
12 ham |
|
Myhammy |
888-321-4567 |
编辑:numpy where 语句:
numpy 由顶部的 import numpy as np 行引入。我们正在创建基于“Comp ID”列的计算列。 numpy 在没有循环的情况下执行此操作。将 where 想象成一个 excel IF() 函数。
df1(return value) = np.where(df[test] > condition, true, false)