pandas 如何使用pandas python将行转换为列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36784908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:06:04  来源:igfitidea点击:

How to convert rows into list using pandas python?

pythonpython-2.7pandas

提问by Sai Rajesh

product,count,value1,value2,value3
A,10,5,3,2
B,8,2,2,4

This is my dataframe. I need output like following format:

这是我的数据框。我需要像以下格式的输出:

product,count,values
A,10,[5,3,2]
B,8,[2,2,4]

回答by Zero

Here's one way

这是一种方法

In [27]: df['values'] = df[['value1', 'value2', 'value3']].values.tolist()

In [28]: df
Out[28]:
  product  count  value1  value2  value3     values
0       A     10       5       3       2  [5, 3, 2]
1       B      8       2       2       4  [2, 2, 4]

In [29]: df.drop(['value1', 'value2', 'value3'], axis=1)
Out[29]:
  product  count     values
0       A     10  [5, 3, 2]
1       B      8  [2, 2, 4]

Details:

细节:

In [35]: df = pd.DataFrame([['A', 10, 5, 3, 2], ['B', 8, 2, 2, 4]],
   ....:                   columns=['product', 'count', 'value1', 'value2', 'value3'])

In [36]: df
Out[36]:
  product  count  value1  value2  value3
0       A     10       5       3       2
1       B      8       2       2       4