我刚刚开始使用Pandas,我发现很难对待像数据帧这样的数据帧。不时地,我不知道如何在不迭代行的情况下做一些事情。
例如,我有一个包含预算信息的数据框。我想提取“供应商”#39;来自简短说明',这是三种潜在形式之一的字符串:
我可以使用以下代码执行此操作,但我无法帮助,但感觉它没有正确使用Pandas。有任何关于改善它的想法吗?
for i, row in dataframe.iterrows():
current = dataframe['short description'][i]
if 'to' in current:
point_of_break = current.index('to') + 3
dataframe['vendor'][i] = current[point_of_break:]
elif 'at' in current:
point_of_break = current.index('at') + 3
dataframe['vendor'][i] = current[point_of_break:]
else:
dataframe['vendor'][i] = current
答案 0 :(得分:3)
我认为您可以to
或at
使用str.split
,然后按str[-1]
选择列表的最后一个值:
我实施了此solution。
df = pd.DataFrame({'A':['blah blah blah to "vendor name"',
'blah blah blah at "vendor name"',
'"vendor name"']})
print (df)
A
0 blah blah blah to "vendor name"
1 blah blah blah at "vendor name"
2 "vendor name"
print (df.A.str.split('[at|to]\s+'))
0 [blah blah blah t, "vendor name"]
1 [blah blah blah a, "vendor name"]
2 ["vendor name"]
Name: A, dtype: object
df['vendor'] = df.A.str.split('(at|to) *').str[-1]
print (df)
A vendor
0 blah blah blah to "vendor name" "vendor name"
1 blah blah blah at "vendor name" "vendor name"
2 "vendor name" "vendor name"
或者使用:
df['vendor'] = df.A.str.split('[at|to]\s+').str[-1]
print (df)
A vendor
0 blah blah blah to "vendor name" "vendor name"
1 blah blah blah at "vendor name" "vendor name"
2 "vendor name" "vendor name"