首页 > 解决方案 > 将一列转换为行和列

问题描述

我一直在使用这种方法,但还没有找到好的解决方案。我正在寻求 python 中的解决方案,但 R 中的解决方案也会有所帮助。

我得到的数据看起来像这样:

import pandas as pd

data = {'Col1': ['Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex' , '200', 'Third Street', '']}

df = pd.DataFrame(data)


             Col1
0             Bob
1             101
3
4             Sue
5             102
6   Second Street
7
8            Alex
9             200
10   Third Street
11

我的真实数据中的模式确实像这样重复。有时有一个空白行(或多于 1 个),有时没有任何空白行。这里重要的部分是我需要将此列转换为一行。

我希望数据看起来像这样。

   Name Address         Street
0   Bob     101   First Street
1   Sue     102  Second Street
2  Alex     200   Third Street

我试过玩这个,但没有任何效果。我的想法是一次遍历几行,将值分配给适当的列,然后逐行构建数据框。

x = len(df['Col1'])
holder = pd.DataFrame()
new_df = pd.DataFrame()

while x < 4:
    temp = df.iloc[:5]
    holder['Name'] = temp['Col1'].iloc[0]
    holder['Address'] = temp['Col1'].iloc[1]
    holder['Street'] = temp['Col1'].iloc[2]

    new_df = pd.concat([new_df, holder])

    df = temp[5:]
    df.reset_index()

    holder = pd.DataFrame()

    x = len(df['Col1'])


new_df.head(10)

标签: pythonrpandastransposedata-wrangling

解决方案


R,

data <- data.frame(
  Col1 = c('Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex' , '200', 'Third Street', '')
)

k<-which(grepl("Street", data$Col1) == TRUE)
j <- k-1
i <- k-2
data.frame(
  Name = data[i,],
  Adress = data[j,],
  Street = data[k,]
)

  Name Adress        Street
1  Bob    101  First Street
2  Sue    102 Second Street
3 Alex    200  Third Street

或者,如果Street不是以数字结尾StreetAdress始终是数字,您也可以尝试

j <- which(apply(data, 1, function(x) !is.na(as.numeric(x)) ))
i <- j-1
k <- j+1

推荐阅读