![](/img/trans.png)
[英]How to choose two rows in a dataframe, calculate the average of both values in each columns and add the new row with the averages in the dataframe
[英]How to make a list for each row of values of two dataframe columns
我有两列,我想为每一行创建一个列表。 因此,每个列表将包含两个值。 该特定行的每一列的值。 例如:
A B
1 2
3 4
5 6
我想为每行值(即[1,2], [3,4], [5,6]
一个列表
您能帮我这个吗?
如果要将其保留在数据框中,可以使用此方法:
df['new'] = df.values.tolist()
>>> df
A B new
0 1 2 [1, 2]
1 3 4 [3, 4]
2 5 6 [5, 6]
否则,如果只需要列表,请使用:
df.values.tolist()
[[1, 2], [3, 4], [5, 6]]
甚至只是df.values
(尽管结果将是一个numpy
数组,而不是列表列表):
>>> df.values
array([[1, 2],
[3, 4],
[5, 6]])
如果您具有以下DataFrame:
print(df)
# A B
#0 1 2
#1 3 4
#2 5 6
将行作为列表获取的一种方法是使用to_records()
:
print([list(x) for x in df.to_records(index=False)])
#[[1, 2], [3, 4], [5, 6]]
或者,如果您想包括索引:
print([list(x) for x in df.to_records(index=True)])
#[[0, 1, 2], [1, 3, 4], [2, 5, 6]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.