Home > Back-end >  Accessing dataframes via lists
Accessing dataframes via lists

Time:07-13

I was trying to change my dataframes, which are in a list dfList = [df1, df2, df3] by accessing them through list references: dfList[0] = pd.dataFrame("bigChange")

Unfortunately this does not actually change my dataframes. I cannot really find anything regarding this online, does anybody know why it is not possible?

CodePudding user response:

Let's say we have a list with 3 dataframes created as below:

import pandas as pd
# initialize list elements
data = [10, 20, 30, 40, 50, 60]

# Create the pandas DataFrame with column name is provided explicitly
df = pd.DataFrame(data, columns=['Numbers'])

dfList = [df, df, df]

You can update the new dataframe in the list by doing:

new_data = [10, 20, 30, 40, 50, 60, 70]
dfList[0] = pd.DataFrame(new_data, columns=['Numbers'])
print(dfList)

CodePudding user response:

You are making a new dataframe instead of changing your old one.

If you have

import pandas as pd
...
dfList = [df1, df2, df3]

and now you

dfList[0] = pd.dataFrame("bigChange") 

df[0] is not df1, rather it is pd.dataFrame("bigChange")

So if you want to modify/change df1 at df[0] then you must access it first and modfiy it not replace it with a new one.

  • Related