简体   繁体   中英

How to fill up each element in a list to given columns of a dataframe?

Let's say I have a dataframe as shown.

在此处输入图像描述

I have a list now like [6,7,6]. How do I fill these to the my 3 desired columns ie,[one,Two,Four] of dataframe? Notice that I have not given column 'three'. Final Dataframe should look like:

在此处输入图像描述

you could do:

columnstobefilled = ["One","Two","Four"]
elementsfill = [6,3,6]
for column,element in zip(columnstobefilled,elementsfill):
    df[column] = element

Since you want the list values to be in specific places you have to specify where each value should go. One way to include this is to use a key value pair object, a dictionary. Once you create that you can use append to include it as a row in your dataframe:

d = {'one':6,'Two':7,'Four':6}
df.append(d,ignore_index=True)

   one  Two  Three  Four
0  2.0  4.0    4.0   8.0
1  6.0  7.0    NaN   6.0

Dataset:

df = pd.DataFrame({'one':2,'Two':4,'Three':4,'Four':8},
                  index=[0])
import pandas as pd
df = pd.DataFrame({'One':2, 'Two':4, 'Three':4, 'Four':8}, index=[0])
new_row = {'One':6, 'Two':7, 'Three':None, 'Four':6}
df.append(new_row, ignore_index=True)
print(df)

output:

   One  Two  Three  Four
0  2.0  4.0    4.0   8.0
1  6.0  7.0    NaN   6.0

You can append a Series:

df = pd.DataFrame([[2, 4, 4, 8]],
                  columns=['One', 'Two', 'Three', 'Four'])

values = [6, 3, 6]
lst = ['One', 'Two', 'Four']

df = df.append(pd.Series(values, index=lst), ignore_index=True)

or a dict:

df = df.append(dict(zip(lst, values)), ignore_index=True)

output:

   One  Two  Three  Four
0  2.0  4.0    4.0   8.0
1  6.0  3.0    NaN   6.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM