[英]How to create a new column in a dataframe with a parsed value from another column where condition is satisfied
Here is an example:这是一个例子:
cars2 = {'Brand': ['Hon*da\nCivic', 'BM^AMT^B6^278.99\n'],
'Price': [22000, 55000]
}
df2 = pd.DataFrame(cars2, columns = ['Brand', 'Price'])
delim = '^'
Output: Output:
Brand Price
0 Hon*da\nCivic 22000
1 BM^AMT^B6^278.99\n 55000
I need:我需要:
Brand Price Allowed Amount
0 Hon*da\nCivic 22000 0
1 BM^AMT^B6^278.99\n 55000 278.99
I tried:我试过了:
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
It gives me this error:它给了我这个错误:
__main__:5: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
How can i fix this?我怎样才能解决这个问题? If there is a better way to do this, please let me know.如果有更好的方法来做到这一点,请告诉我。 Thanks.谢谢。
You can do like this:你可以这样做:
df2['Allowed_Amount'] = df2['Brand'].str.split('^',-1).str[3]
df2['Allowed_Amount'] = df2['Allowed_Amount'].str[:-2]
You can also make it one line:您也可以将其设为一行:
df2['Allowed_Amount'] = df2['Brand'].str.split('^',-1).str[3].str[:-2]
The first line will split the "^" by doing from last and get the last value.第一行将通过 from last 拆分“^”并获取最后一个值。 Then in second line we removing the new line !然后在第二行我们删除新行!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.