简体   繁体   English

如何使用来自满足条件的另一列的解析值在 dataframe 中创建新列

[英]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.

相关问题 如何替换满足条件的列中的值? - How to replace value in a column where a condition is satisfied? 如何从 dataframe 中的另一列按条件创建新组? - How to create new group by condition from another column in dataframe? 使用来自另一个数据帧的 if 条件在 Pandas 数据帧中创建一个新列 - create a new column in pandas dataframe using if condition from another dataframe 如果满足条件,则在新列中分配一个值 - Assign a value within a new column if a condition is satisfied Pandas 根据来自另一个 dataframe 的计数和条件创建新列 - Pandas Create new column based on a count and a condition from another dataframe Pandas 数据框根据另一列的条件创建新行 - Pandas dataframe create new rows based on condition from another column 创建新的数据框列,保留另一列的第一个值 - Create new dataframe column keeping the first value from another column 如何在 Pandas 中创建新列,条件是重复另一列的值? - How to create new column in Pandas with condition to repeat by a value of another column? 如何根据其他 dataframe 的条件在 dataframe 中创建新列? - How to create new column in dataframe based on condition from other dataframe? Pandas:添加新列并按条件从另一个dataframe赋值 - Pandas: Add new column and assigning value from another dataframe by condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM