I am a Python beginner and have a problem with a for loop. I want to assign a list of numbers to different DataFrame columns. Manually, I can assign my values with the correct code, but copy and paste isn't a good style for programming.
The correct manual code looks like this:
df = pd.DataFrame(columns=['a', 'b', 'c'], index=range(100))
num = [100,200,300]
df['a'] = num[0]
df['b'] = num[1]
df['c'] = num[2]
df.head()
a b c
0 100 200 300
1 100 200 300
2 100 200 300
3 100 200 300
4 100 200 300
My for loop is the following:
df = pd.DataFrame(columns=['a', 'b', 'c'], index=range(100))
for s in strings:
for n in num:
df[s] = n
df.head()
a b c
0 300 300 300
1 300 300 300
2 300 300 300
3 300 300 300
4 300 300 300
Can anyone help me to write a for loop that works like my manual code?
If you already have an existing DataFrame, use assign
:
df.assign(**dict(zip(df, num)))
You don't have to modify all columns if you don't need to!
df = pd.DataFrame(columns=['a', 'b', 'c', 'd', 'e'], index=range(100))
df.assign(**dict(zip(['a', 'c', 'e'], num))).head()
a b c d e
0 100 NaN 200 NaN 300
1 100 NaN 200 NaN 300
2 100 NaN 200 NaN 300
3 100 NaN 200 NaN 300
4 100 NaN 200 NaN 300
The simplier is to pass a list to the DataFrame
constructor, then no loop is necessary:
df = pd.DataFrame([[100,200,300]], columns=['a', 'b', 'c'], index=range(100))
print (df.head())
a b c
0 100 200 300
1 100 200 300
2 100 200 300
3 100 200 300
4 100 200 300
But if you want a loop solution:
df = pd.DataFrame(columns=['a', 'b', 'c'], index=range(100))
num = [100,200,300]
cols = ['a','b','c']
for c, val in zip(cols, num):
df[c] = val
print (df.head())
a b c
0 100 200 300
1 100 200 300
2 100 200 300
3 100 200 300
4 100 200 300
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.