Split data into 3 column dataframe

廉价感情. 提交于 2021-01-27 17:36:38

问题


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.

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

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

回答1:


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:



来源:https://stackoverflow.com/questions/60997482/split-data-into-3-column-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!