簡體   English   中英

如何從給定的熊貓數據幀創建子數據幀?

[英]How to create a sub data-frame from a given pandas data-frame?

我編寫了一個代碼,該代碼從給定的數據集中讀取並將整個txt文件轉換為熊貓數據幀(經過一些預處理)

  • 緯度代表行,並顯示在列表中。
  • 經度代表各列,並顯示在單獨的列表中。

現在,我想從我創建的原始數據框架中創建一個較小的數據框架(以便更容易理解和解釋數據)並執行計算。 為此,我跳過了每10個元素,創建了一個較小的18列。 這很好。 讓我們將此新列稱為new_column。

現在,我要做的是遍歷每一行,並針對行k和new_column j的每個值,將其添加到新矩陣或數據幀中。
例如。 如果第10行和new_column 12的值是“ x”,我想將此“ x”添加到相同的位置,但要在新的數據幀(或矩陣)中。

我已經編寫了以下代碼,但我不知道該如何執行那部分,因此我可以執行上述操作。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy import interpolate
# open the file for reading
dataset = open("Aug-2016-potential-temperature-180x188.txt", "r+")

# read the file linewise
buffer = dataset.readlines()

# pre-process the data to get the columns
column = buffer[8]
column = column[3 : -1]

# get the longitudes as features
features = column.split("\t")

# convert the features to float data-type
longitude = []

for i in features:
    if "W" in features:
        longitude.append(-float(i[:-1]))   # append -ve sign if "W", drop the "W" symbol
    else:
        longitude.append(float(i[:-1]))    # append +ve sign if "E", drop the "E" symbol

# append the longitude as columns to the dataframe
df = pd.DataFrame(columns = longitude)

# convert the rows into float data-type
latitude = []

for i in buffer[9:]:
    i = i[:-1]
    i = i.split("\t")

    if i[0] != "":
        if "S" in i[0]:     # if the first entry in the row is not null/blank
            latitude.append(-float(i[0][:-1]))  # append it to latitude list; append -ve for for "S"
            df.loc[-float(i[0][:-1])] = i[1:]   # add the row to the data frame; append -ve for "S" and drop the symbol
        else:
            latitude.append(float(i[0][:-1]))
            df.loc[-float(i[0][:-1])] = i[1:]

print(df.head(5))

temp_col = []
temp_row = []
temp_list = []

temp_col = longitude[0 : ((len(longitude) + 1)) : 10]

for iter1 in temp_col:
    for iter2 in latitude:
        print(df.loc[iter2])

我也在這里提供到數據集的鏈接

(下載以.txt結尾的文件,並從與.txt文件相同的目錄中運行代碼)

我是numpy,pandas和python的新手,編寫這小段代碼對我來說是一項艱巨的任務。 如果能在這方面得到一些幫助,那將是很棒的。

歡迎來到NumPy / Pandas的世界:)關於它的最酷的事情之一是將矩陣上的動作抽象為簡單的命令的方式,在大多數情況下,無需編寫循環。

使用更可笑的代碼,您無需進行很多工作。 以下是我嘗試重現您所說的內容。 我可能會誤解了,但希望它能使您更加接近/指出正確的方向。 隨時要求澄清!

import pandas as pd

df = pd.read_csv('Aug-2016-potential-temperature-180x188.txt', skiprows=range(7))
df.columns=['longitude'] #renaming
df = df.longitude.str.split('\t', expand=True)
smaller = df.iloc[::10,:] # taking every 10th row
df.head()

因此,如果我理解正確(請確保),您將擁有一個龐大的數據集,其中行和列為緯度和經度。 您想對此進行抽樣處理(計算,探索等)。 因此,您將創建一個行的子列表,並希望基於這些行創建一個新的數據框。 這個對嗎?

如果是這樣的話:

df['temp_col'] = [ 1 if x%10 == 0 else 0 for x in range(len(longitude))]
new_df = df[df['temp_col']>0].drop(['temp_col'],axis = 1]

並且如果您還想刪除一些列:

keep_columns = df.columns.values[0 :len(df.columns) : 10]
to_be_droped = list(set(df.columns.values) - set(keep_columns))
new_df = new_df.drop(to_be_droped, axis = 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM