加载数据集,其中每个观测值用python拆分为两行
我正在尝试导入一个数据集,其中每个观测值被分成两行。我读取了数据并命名了一些列,数据框如下所示:加载数据集,其中每个观测值用python拆分为两行,python,pandas,data-wrangling,Python,Pandas,Data Wrangling,我正在尝试导入一个数据集,其中每个观测值被分成两行。我读取了数据并命名了一些列,数据框如下所示: crim zn indus chas nox rm age dis rad tax ptratio 20 0.00632 18.00 2.310 0 0.5380 6.5750 65.20 4.0900 1 296.0 15.30 21 396.90 4.98 24.00 None
crim zn indus chas nox rm age dis rad tax ptratio
20 0.00632 18.00 2.310 0 0.5380 6.5750 65.20 4.0900 1 296.0 15.30
21 396.90 4.98 24.00 None None None None None None None None
22 0.02731 0.00 7.070 0 0.4690 6.4210 78.90 4.9671 2 242.0 17.80
23 396.90 9.14 21.60 None None None None None None None None
...
第21行中的三个值应位于上一行的三个新列中。整个数据帧也是如此。我该怎么做?
谢谢您只需移动您想要的序列,然后使用移动即可。然后,可以将移位的列添加到数据帧中,并且可以从中每隔一行删除一行 您可以按如下方式构造数据:
import pandas as pd
headers = ["crim", "zn", "indus", "chas", "nox", "rm", "age", "dis", "rad", "tax", "ptratio"]
vals = [[0.00632, 18.00, 2.310, 0, 0.5380, 6.5750, 65.20, 4.0900, 1, 296.0, 15.30],
[396.90, 4.98, 24.00, None, None, None, None, None, None, None, None],
[0.02731, 0.00, 7.070, 0, 0.4690, 6.4210, 78.90, 4.9671, 2, 242.0, 17.80],
[396.90, 9.14, 21.60, None, None, None, None, None, None, None, None]]
df = pd.DataFrame(columns=headers, data=vals)
# add shifted rows
df['new_crim'] = df['crim'].shift(-1)
df['new_zn'] = df['zn'].shift(-1)
df['new_indus'] = df['indus'].shift(-1)
# remove every second row
df_cleaned = df.iloc[::2]
df_cleaned.reset_index(inplace=True, drop=True)
print(df_cleaned)
输出:
crim zn indus chas nox rm age dis rad tax ptratio new_crim new_zn new_indus
0 0.00632 18.0 2.31 0.0 0.538 6.575 65.2 4.0900 1.0 296.0 15.3 396.9 4.98 24.0
1 0.02731 0.0 7.07 0.0 0.469 6.421 78.9 4.9671 2.0 242.0 17.8 396.9 9.14 21.6
与最初使用pandas读取文件内容不同,我将“手动”逐行读取文件,然后从内容创建数据帧。建议:
将熊猫作为pd导入
进口稀土
将open(“path/to/file.txt”)作为f:
#阅读第一行,即标题,在空格处拆分并删除换行符
headers=re.split(“+”,f.readline()。replace(“\n”,”))
内容=[]
尽管如此:
#一次读两行,因为一行横跨两行
line=f.readline()+f.readline()
#如果该行为空字符串,则表示文件已结束。
如果行==“”:
打破
#在空格处拆分文件并删除换行符。
content.append(re.split(“+”,line.replace(“\n“,”))
#结果是一个列表列表,我们可以从中轻松创建数据帧。
df=pd.DataFrame(内容[1:])
DataFrame没有标题,但可以根据需要从标题
-变量轻松添加标题
这种方法的优点在于它很灵活,而且在我看来,很容易理解和扩展到不同的用例