简体   繁体   English

如何连接 Dataframe Pandas 并将其转换为 Python 上的多维列表

[英]How to Concat Dataframe Pandas and Convert it into Multidimensional List on Python

i have a dataset structure like this:我有一个这样的数据集结构:

| id | age | name | income |
----------------------------
|  0 |  9  |  AA  | 300    |
|  1 |  6  |  ZZ  | 100    |

and how to extract age and income and then combining again and convert those data into multidimentional list like this:以及如何提取ageincome ,然后再次组合并将这些数据转换为多维列表,如下所示:

[
  [9, 300], 
  [6, 100]
]

i've tried a concate from pandas documentation, but it goes wrong when i converted it into list.我已经尝试了concate文档的连接,但是当我将它转换为列表时出错了。 my code is:我的代码是:

dataframe = pd.read_csv('my.csv')
data = pd.concat([dataset['age'], dataset['income']], axis=1)

everything is fine if i type print(data) , the result is dataframe is already merged.如果我输入print(data)一切都很好,结果是 dataframe 已经合并。 But if i type print(list(data)) the result i received is only header's name appear.但是如果我输入print(list(data))我收到的结果只是标题的名称出现。

maybe you guys know how to solve my problem, any help will be appreciated也许你们知道如何解决我的问题,任何帮助将不胜感激

thanks谢谢

I'm not sure to understand why using merge .我不确定为什么要使用merge

Assuming you have a dataframe like假设你有一个 dataframe 之类的

#    id  age name  income
# 0   0    9   AA     300
# 1   1    6   ZZ     100

You can try values followed by numpy.ndarray.tolist :您可以尝试后跟numpy.ndarray.tolistvalues

df[["age", "income"]].values.tolist()
# [[9, 300], [6, 100]]
print(type(df[["age", "income"]].values.tolist()))
# <class 'list' >

values return a numpy array: values返回 numpy 数组:

print(type(df[["age", "income"]].values))
# <class 'numpy.ndarray'>
print(df[["age", "income"]].values)
# [[  9 300]
#  [  6 100]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM