【问题标题】:Python Read data from CSVPython 从 CSV 读取数据
【发布时间】:2021-03-26 11:01:05
【问题描述】:

我有一个 Python 程序,可以从 csv 读取数据,我有 2 个问题。

  1. 假设在文件中我有从 1990 年到 2020 年的数据。我可以使用什么命令仅获取 2000 年以上的年份?

  2. 假设文件中的日期具有这种格式 '2000-12-02' 我如何将其添加到列表中,因为我认为它们目前是字符串,我无法进行预测,因为我需要字符串。

我将放在这里的代码与问题没有关联,只是为了让您可以看到我使用的导入和东西。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model


regr = linear_model.LinearRegression()

df = pd.read_csv("net_monthly_average_earnings.csv")

print(df.head())

X = df[['Year']]
y = df[['Earnings']]

regr.fit(X, y)
earnings_predict = regr.predict(X)
plt.plot(X, y, 'o')
plt.plot(X, earnings_predict)

X_future = np.array(range(2021, 2030))
X_future = X_future.reshape(-1, 1)
future_predict = regr.predict(X_future)
plt.plot(X_future, future_predict, 'o')
plt.xlabel('Year')
plt.ylabel('Earning')
plt.title('Average salary in Romania + future predictions')
plt.show()

【问题讨论】:

    标签: python pandas matplotlib scikit-learn


    【解决方案1】:
    df['date'] = pd.to_datetime(df['date'])
    df['year'], df['month'] = df['date'].dt.year, df['date'].dt.month
    df
    

    您可以使用“if”语句来获取您想要的年份。 以您为例-

    if X>2000:
        print(X)
    

    或者您可以使用 SQL 来选择您希望进入数据库的年份(在创建 init 函数之后)

    def year_select(self,CURRENT_TIMESTAMP):
        self.cur.execute("SELECT YEAR IF>2000")
    

    将日期放入列表中:

    import pandas as pd
    
    start = '2015-08-01' #YYY-MM-DD
    end = '2020-07-06'
    
    pd.date_range(start, end)
    
    # to start from today
    
    pd.date_range(pd.Timestamp.today(), end)
        
    

    【讨论】:

    • 没问题的朋友!
    猜你喜欢
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多