我一直遇到这种用法,但还没有找到好的解决方案。我正在寻求 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)
最佳答案
在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
不是以 Street
结尾,但 Adress
始终是数字,您也可以尝试
j <- which(apply(data, 1, function(x) !is.na(as.numeric(x)) ))
i <- j-1
k <- j+1
关于python - 将一列转换为行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69833702/