Home > Enterprise >  How to simplify this loop (DataFrame in pandas)
How to simplify this loop (DataFrame in pandas)

Time:12-02

Hey I have a DataFrame in which values of a column Values are lists, where each list contain a strings with 3 characters. For a values from values_list I want to replace last character by "I" in each list in Values column. That is my current code:

for i in range(len(data["Values"])):
    for k in range(len(data.iloc[i]["Values"])):
        if data.iloc[i]["Values"][k] in values_list:
            data.iloc[i]["Values"][k] = data.iloc[i]["Values"][k][:2]   "I"

How can I rewrite it in more proper way?

CodePudding user response:

Not really clear on what you are trying to do, but I think this is what you mean.

You can define the function and then use .map() on that column:

import pandas as pd

data = pd.DataFrame({'Values':[['aaa','bbb','ccc'],
                               ['ddd','eee','fff']]})


print(data)

values_list = ['aaa', 'ccc', 'eee']

def subI(value_list):
    value_list = [x[:-1]   'I' if x in values_list else x for x in value_list]
    return value_list

data['Values'] = data['Values'].map(subI)

print(data)

Output:

print(data)
            Values
0  [aaa, bbb, ccc]
1  [ddd, eee, fff]
            Values
0  [aaI, bbb, ccI]
1  [ddd, eeI, fff]
  • Related