[英]How do you add Values to each row of the Dataframe Using Pandas?
How do I add data to each row of my dataframe.如何将数据添加到 dataframe 的每一行。
from collections import namedtuple
import pandas as pd
People = namedtuple('People',['id','name'])
dictionary = {1: People(1,'Rodger'), 2: People(2,'Betty'), 3: People(1,'Susie')}
keys = list(map(int, dictionary.keys())) # [1, 2, 3]
for k in dictionary:
df = pd.DataFrame({'id': keys, 'name': dictionary[k].name})
print(df)
It doesn't add each name to a row that corresponds to its id.它不会将每个名称添加到与其 id 对应的行中。 It fills every row of the name column with the value 'Rodger'.
它用值“Rodger”填充名称列的每一行。 Why is this?
为什么是这样?
[current output]
id: name:
1 Susie
2 Susie
3 Susie
[desired output]
id: name:
1 Rodger
2 Betty
3 Susie
The problem happens because you are overriding the dataframe at every iteration:出现问题是因为您在每次迭代时都覆盖了 dataframe:
for k in dictionary:
df = pd.DataFrame({'id': keys, 'name': dictionary[k].name}) # override using all keys but next name in sequence
A solution:一个解法:
df = pd.DataFrame({'id': keys, 'name': [item.name for item in dictionary.values()]})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.