python - 将一列转换为行和列
问题描述
我一直在使用这种方法,但还没有找到好的解决方案。我正在寻求 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
推荐阅读
- javascript - 在映射 json 呈现的每个组件上调用 React Native onPress
- ansible - 如何指示 Ansible 远程节点命令在远程节点上查找文本资源文件
- arrays - 确定从 n 个数组中选择 1 个唯一元素的可能性的算法
- ios - 自动签名无法解决“myProject”目标的权利问题
- r - 使用过滤后的数据框 RShiny 下载 CSV
- c++ - c ++ 11多态映射键静态断言失败:哈希函数必须可以使用键类型的参数调用
- android - 在android中生成用户数据报告
- excel - 如果单元格的第一个字符是 GUF 则删除 GUF 如果不是留空
- mouseevent - 仅使用鼠标中键的 Openlayer 平移
- import - Google Import Offline Conversions 设置用户名和密码