如何将列表中的值分配给数据框的列/行?

时间:2019-10-18 19:50:21

标签: python pandas dataframe

如何将列表中的值分配给python数据框中的列/行?

反之,我只能使用以下命令执行list_name = df.iloc[x, y]。但是,当我尝试命令df.iloc[x, y] = list_name时,我无法将list_name中的值转换为df.iloc[x, y]

在这种情况下,将list_name中的值转换为df.iloc[x, y]的正确命令应该是什么?

1 个答案:

答案 0 :(得分:0)

不幸的是,iloc索引的设计目的不是像获取一样多用。但是,如果要像示例中那样使行x和列y保持动态,则有一些解决方法。

对于以下内容,我使用pandas.Dataframe documentation example作为起始,如下所示。

my_dict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]

df = pandas.DataFrame(my_dict)

步骤1:获取行

很简单,您可以通过加入df.iloc[x]来排行。如果您有x = 1,在上面的示例中,我们将得到:

> df.iloc[x]
a    100
b    200
c    300
d    400

当我们有这样的行时,我们可以使用索引300获得该值'c'

> df.iloc[x]['c']
300

但是,如果只有列索引,则需要首先获取此名称。

步骤2:获取列名

要将索引y转换为列名,我们可以使用dataframe axes property,如下所示:

> y = 2
> df.axes[1][y]
c

第3步:放在一起

现在,如果我们要使用xy来引用数据帧中的特定条目,我们可以先获取row然后获取{{1} }:

column

或者,如果要单行处理:

row = df.iloc[x]
column = df.axes[1][y]
row[column] = desired_value

完整示例

这是实际操作的完整示例。

df.iloc[x][df.axes[1][y]]

最后的打印声明给我们:

import pandas

x = 1
y = 2

my_dict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]

df = pandas.DataFrame(my_dict)

desired_value = 999

row = df.iloc[x]
column = df.axes[1][y]
row[column] = desired_value

print(df)

请注意我们用 a b c d 0 1 2 3 4 1 100 200 999 400 2 1000 2000 3000 4000 设置的999

相关问题