简体   繁体   English

将数据拆分为 3 列数据框

[英]Split data into 3 column dataframe

I'm having trouble parsing a data file into a data frame.我在将数据文件解析为数据框时遇到问题。 When I read the data using pandas I get a one column data frame with all the information.当我使用 Pandas 读取数据时,我会得到一个包含所有信息的单列数据框。

Server    
7.14.182.917 - - [20/Dec/2018:08:30:21 -0500] "GET /tools/performance/log/lib/ui-bootstrap-tpls-0.23.5.min.js HTTP/1.1" 235 89583
7.18.134.196 - - [20/Dec/2018:07:40:13 -0500] "HEAD / HTTP/1.0" 502 -
...

I want to parse the data in three columns.我想解析三列中的数据。 I tried using df[['Server', 'Date', 'Address']] = pd.DataFrame([ x.split() for x in df['Server'].tolist() ]) but I'm getting an error ValueError: Columns must be same length as key Is there a way to parse the data to have 3 columns as follows我尝试使用df[['Server', 'Date', 'Address']] = pd.DataFrame([ x.split() for x in df['Server'].tolist() ])但我得到错误ValueError: Columns must be same length as key有没有办法将数据解析为具有 3 列,如下所示

Server        Date                          Address                               
7.14.182.917  20/Dec/2018:08:30:21 -0500.   "GET /tools/performance/log/lib/ui-bootstrap-tpls-0.23.5.min.js HTTP/1.1" 235 89583

Multiple approaches can be taken here depending on the input file type and format.根据输入文件类型和格式,可以在此处采用多种方法。 If the file is a valid string path, try these approaches (more here) :如果文件是有效的字符串路径,请尝试以下方法(更多信息)

import pandas as pd
# approach 1
df = pd.read_fwf('inputfile.txt')

# approach 2
df = pd.read_csv("inputfile.txt", sep = "\t") # check the delimiter

# then select the columns you want
df_subset = df[['Server', 'Date', 'Address']]

Full solution:完整解决方案:

import pandas as pd

# read in text file
df = pd.read_csv("test_input.txt", sep=" ", error_bad_lines=False)

# convert df to string
df = df.astype(str)

# get num rows
num_rows = df.shape[0]

# get IP from index, then reset index
df['IP'] = df.index

# reset index to proper index
new_index = pd.Series(list(range(num_rows)))
df = df.set_index([new_index])

# rename columns and drop old cols
df = df.rename(columns={'Server': 'Date', 'IP': "Server"})

# create Date col, drop old col
df['Date'] = df.Date.str.cat(df['Unnamed: 1'])
df = df.drop(["Unnamed: 1"], axis=1)

# Create address col, drop old col
df['Address'] = df['Unnamed: 2'] + df['Unnamed: 3'] + df['Unnamed: 4']
df = df.drop(["Unnamed: 2","Unnamed: 3","Unnamed: 4"], axis=1)

# Strip brackets, other chars
df['Date'] = df['Date'].str.strip("[]")
df['Server'] = df["Server"].astype(str)
df['Server'] = df['Server'].str.strip("()-'', '-',")

Returns:返回:

在此处输入图片说明

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

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