简体   繁体   English

如何使用 Pandas 向 Dataframe 的每一行添加值?

[英]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.

相关问题 在熊猫数据框中,如何在迭代的每一行的末尾添加一个值? - In a pandas dataframe, how do you add a value to the end of each row in iterrows? 如何添加一个简单的计数器列,每列增加1到Pandas DataFrame? - How do you add a simple counter column that increases by one in each row to a Pandas DataFrame? 如何在熊猫的前一行中添加数组? - How do you add an array to each previous row in pandas? 使用熊猫,如何逐行遍历数据帧,但每一行都是其自己的数据帧 - Using pandas, how do I loop through a dataframe row by row but with each row being its own dataframe 您如何遍历 pandas Dataframe 中的组,对每个组进行操作,然后将值分配给原始 Dataframe? - How do you iterate through groups in a pandas Dataframe, operate on each group, then assign values to the original dataframe? 使用 Pandas,如何将现有数据帧行添加到具有现有值的另一个数据帧行? - Using Pandas, how would I add an existing dataframe row to another dataframe row with existing values? 如何在 pandas dataframe 的每一行中的选定列中找到两个最低值? - How do I find the two lowest values across selected columns in each row of a pandas dataframe? 如何有效检查熊猫数据框中每一行的值的连续范围? - How do I check for continuous range of values in each row of pandas dataframe effectively? 如何在pandas数据帧的每一行的开头添加动态数量的空格? - How do I add a dynamic number of white spaces to the beginning of each row of a pandas dataframe? 如何根据每行中的条件将多个字符串添加到 pandas dataframe 中的列中? - How do I add multiple strings to a column in a pandas dataframe based on conditions in each row?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM