Home > OS >  How to access a value in a DataFrame where df.columns value have the following string with ".L&
How to access a value in a DataFrame where df.columns value have the following string with ".L&

Time:10-19

I have the following Dataframe

Date            A        AAPL         FB    GOOG        MSFT  WISE.L

2021-10-15  153.270004  144.839996  324.76001  2833.5  304.209991   900.0

I am trying to write a code that will check if the df.columns have any string with ".L" at the end, and then change it's value. For example: In the df above I want to reach 900.0 and change it.

Note: the strings that contain ".L" can be numerous, and have different name, all depends on user input, so i'll need to fetch all of them and change them at once.

Is it possible to do it or I should find out a different way to do it?

--Editing my question after @Kosmos suggestion

Create a list of the columns which ends with “.L”.

col_list = [col for col in df.columns of col.endswith(”.L”)] 

@Kosmos suggetion works well so I tweaked it to:

for col in df.columns:
    if col.endswith(".L"):
        #do something

In the #do something space i'll need to convert the value stored in the columns with ".L" values (convert the number to USD) which I already know how to do, the issue is how can I access and change it on the frame without exctracting and inserting it again?

CodePudding user response:

Create a list of the columns which ends with “.L”.

col_list = [col for col in df.columns if col.endswith(”.L”)]  

The following operation gives a frame with only the columns which ends with “.L”.

df.loc[:,col_list]

After update
1st Solution

I see your problem. The list comprehension i suggested is not immediately suitable (it could be fixed using a custom function). I think that you are very close to done with your new suggestion. Editing the df column-wise can be done as such:

for col in df.columns:
    if col.endswith(".L"):
        df.loc[:,col] = df.loc[:,col]*arbitrary_value

2nd solution Note that if all columns in col_list is aggregated using the same value (e.g. converting to USD), the following can also be done:

df.loc[:,col_list] = df.loc[:,col_list]*arbitrary_value
  • Related