我有以下数据集:
df = pd.DataFrame([
{'Phone': 'Fax(925) 482-1195', 'Fax': None},
{'Phone': 'Fax(406) 226-0317', 'Fax': None},
{'Phone': 'Fax+1 650-383-6305', 'Fax': None},
{'Phone': 'Phone(334) 585-1171', 'Fax': 'Fax(334) 585-1182'},
{'Phone': None, 'Fax': None},
{'Phone': 'Phone(334) 585-1171', 'Fax': 'Fax(334) 585-1176'}]
)应该是这样的:

我试图做的是:对于我看到的每一行“传真”,我想截断它,并将此记录传送到“传真”列。
首先,我试图只查询与此筛选的匹配:
df[df['Phone'].str.contains("Fax") == True, "Fax"] = df[df['Phone'].str.contains("Fax") == True]但是它不起作用,错误是:"TypeError: unhashable type:'Series'“。
有什么想法吗?
发布于 2022-09-30 22:52:31
你有一堆行,也就是说,一串数据。最简单的方法是在将每一行添加到dataframe之前对其进行按摩。
rows = [ ... ]
def get_contacts(rows):
for row in rows:
phone, fax = row['Phone'], row['Fax']
if 'Fax' in phone:
phone, fax = None, phone
yield phone, fax
df = pd.DataFrame(get_contacts(rows))您可以使用这样的过滤器强制使用str而不是None:
...
yield clean(phone), clean(fax)
...
def clean(s, default=''):
if s is None:
return default
return s如果你真的喜欢坚持使用熊猫,你可能会想
df.Phone包含“传真”的行的掩码,然后df['Fax']中,然后df['Phone']条目。您可以自行验证/调试每个步骤
如果你选择走这条路,请邮寄你的最终解决方案。
发布于 2022-10-01 01:38:50
import numpy as np
import pandas as pd
condition = df["Phone"].str.contains("fax", case=False)
df = df.assign(
Fax=np.where(condition, df["Phone"], df["Fax"]),
Phone=np.where(condition, "", df["Phone"])
).fillna("")
print(df)
Phone Fax
0 Fax(925) 482-1195
1 Fax(406) 226-0317
2 Fax+1 650-383-6305
3 Phone(334) 585-1171 Fax(334) 585-1182
4
5 Phone(334) 585-1171 Fax(334) 585-1176https://stackoverflow.com/questions/73914589
复制相似问题