2

I have two lists in one there are columns names which will be dynamic and another list values too. how I can map that map to my dataframe df. so for this I have give those list as static. but in my program will be dynamic.

df = pd.DataFrame(columns = ['ABC', 'LMN', 'XYZ','PQR']
columns = ['LMN','PQR']
values = ['234','654']

So far I have tried this

for i in range(len(values)):
            df[columns[i]] = np.where(df[columns[i]] == columns[i], values[i], 0)

Expected output: -

Id  ABC  LMN  XYZ  PQR
0    0   234  0    654

3 Answers 3

2

You can get a Pandas series with elements from list values with all the columns in df as index and fill-up undefined entries with 0, then append it to df, as follows:

s = pd.Series(data=values, index=columns).reindex(df.columns).fillna(0)
df = df.append(s, ignore_index=True)

Result:

print(df)


  ABC  LMN XYZ  PQR
0   0  234   0  654

We use .reindex() so that the series already has the full set of index corresponding to the full set of columns of df. Consequently, we can fill-up the NaN values with 0 before appending to df.


Alternatively, we can also simplify the steps as follows:

s = pd.Series(data=values, index=columns)
df = df.append(s, ignore_index=True).fillna(0)

This version is simpler than the previous version without the need to use .reindex(). However, at the .fillna() step, it will also fill-up NaN values of previous rows.

Depending on whether you want to retain NaN values of previous rows or not. If you don't need to keep NaN values of previous rows, this is a simpler version to go for. Otherwise, the previous version is more appropriate.

Sign up to request clarification or add additional context in comments.

Comments

2

You can also do this by append() ,Dataframe() and fillna() method:

df=df.append(pd.DataFrame(columns=columns, data=[values])).fillna(0)

If you print df you will get:

print(df)
>>>

   ABC  LMN  XYZ  PQR
0  0    234  0    654

Comments

1

You can try like this:

df = pd.DataFrame(columns = ['ABC', 'LMN', 'XYZ','PQR'])
columns = ['LMN','PQR']
values = ['234','654']

pd.concat([df, pd.DataFrame(columns=columns, data=[values])])

   ABC  LMN  XYZ  PQR
0  NaN  234  NaN  654

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.