这里是一个例子:
cars2 = {'Brand': ['Hon*da\nCivic', 'BM^AMT^B6^278.99\n'],
'Price': [22000, 55000]
}
df2 = pd.DataFrame(cars2, columns = ['Brand', 'Price'])
delim = '^'
输出:
Brand Price
0 Hon*da\nCivic 22000
1 BM^AMT^B6^278.99\n 55000
我需要:
Brand Price Allowed Amount
0 Hon*da\nCivic 22000 0
1 BM^AMT^B6^278.99\n 55000 278.99
我尝试过:
for field in range(0, len(df2)):
if 'AMT'+delim+'B6' in df2.iloc[field]['Brand']:
df2.iloc[field]['Allowed_Amount'] = df2.iloc[field]['Brand'].split("AMT"+delim+"B6")[1][1:].split('\n')[0]
else:
df2.iloc[field]['Allowed_Amount'] = 0
它给了我这个错误:
__main__:5: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
我该如何解决?如果有更好的方法可以进行此操作,请告诉我。谢谢。
答案 0 :(得分:0)
您可以这样做:
df2['Allowed_Amount'] = df2['Brand'].str.split('^',-1).str[3]
df2['Allowed_Amount'] = df2['Allowed_Amount'].str[:-2]
您也可以将其设置为一行:
df2['Allowed_Amount'] = df2['Brand'].str.split('^',-1).str[3].str[:-2]
第一行将从“ last”开始分割“ ^”并获得最后一个值。然后在第二行中删除新行!