简体   繁体   English

如何将列表中的每n个术语转换为Pandas import中的一列?

[英]How do I transpose every nth term in a list to a column from Pandas import?

I imported some data. 我导入了一些数据。 And its just one line 它只是一行

 Jane  
 M  
 52,000 
 NYC 
 Mike  
 M  
 38,000 
 LA  

AND so on I have 1000 lines 依此类推,我有1000行

how do I get it to be 我该怎么做

Name Sex salary City 
Jane  M  52,000 NYC 
Mike  M  38,000 LA   

So every 5 lines make it a column I guess. 因此,我猜每5行将其列为一列。

Thanks 谢谢

Simply reshape . 简单地reshape

a = df['column_name'].to_numpy().reshape(-1, 4)

Notice that 4 above means 4 columns, which looks like is what you have after your edit. 请注意,上面的4表示4列,看起来像是您编辑后的内容。 Before, it looked like you had 5 columns. 以前,您好像有5列。 Just adapt to whatever you have 只要适应你所拥有的


To make it a DataFrame 使它成为一个DataFrame

pd.DataFrame(a, columns=['Name', 'Sex', 'salary', 'City'])

Since your question is not well defined and it changed a lot after your edit, I hope the above can help being a lead on what you need 由于您的问题定义不明确,并且在编辑后发生了很大变化,因此希望以上内容可以帮助您找到所需的线索

You need to grab every subseries of 5 elements ( iloc[] ), transform them ( .T ) and concat them. 你需要抓住5个元素(每个子系列iloc[]改造他们( .T )和concat他们。

data = pd.concat([df.iloc[s:s+4].reset_index(drop=True).T for s in range(0,len(df), 5)]).reset_index(drop=True)
data.columns = ['Name', 'Sex', 'City', 'Salary']
data['Sex'] = data['Sex'].str[0]

Output: 输出:

    Name    Sex     City    Salary
0   MiKE    M       NYC     52,000
1   MiKE    M       NYC     52,000

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

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