我正在处理一个数据集,其中的列被命名为标题。其值如前所述。
df = pd.DataFrame(data={"location":["düsseldorf, nordrhein-westfalen, germany",
"durbanville , cape town, cape town , south africa"]})
我想将此列划分为['city', 'state', 'country']
。请注意,第二行有重复项。
我尝试了以下方法,但这不处理重复项:
location = df.location.str.split(', ', n=2, expand=True)
location.columns = ['city', 'state', 'country']
最佳答案
您可以使用 itertools
docs 中提供的 unique_everseen
配方。 ,也可在第三方库中使用,例如 toolz.unique
.
该逻辑可以合并到迭代df['location']
的列表理解中。这可能比 Pandas 基于字符串的方法更有效,后者不提供矢量化功能。
from toolz import unique
res = pd.DataFrame([list(unique(map(str.strip, i.split(',')))) for i in df['location']])
res.columns = ['city', 'state', 'country']
print(res)
city state country
0 düsseldorf nordrhein-westfalen germany
1 durbanville cape town south africa
关于python - 如何在给定的数据框中划分列 'location'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52567930/