我目前有一个字典,由 11 个不同大小的导入数据框组成。我想添加一个条件,以便我只导入包含一定数量观察值的数据帧,例如 50k。
import pandas as pd
import numpy as np
import glob
monthly_files = glob.glob("Module 6/data/Month_xx_data/*")
file_name = os.path.basename(monthly_files[0])
monthly_data = {}
for file_path in monthly_files:
month = os.path.basename(file_path)[:-4]
monthly_data[month]=pd.read_csv(file_path)
monthly_data
字典部分结果:
'{'Month-01': Account_ID Transaction_Timestamp Factor_A Factor_B Factor_C
0 5 2009-01-08T00:16:41Z 2 6 六
1 16 2009-01-20T22:40:08Z 2 6 六
2 28 2009-01-19T13:24:55Z 2 6 六
3 40 2009-01-05T16:10:58Z 2 6 六
4 62 2009-01-21T19:13:13Z 2 6 六
……………………
54530 144190 2009-01-13T11:53:44Z 2 6 六
54531 144191 2009-01-01T12:54:50Z 7 6 MC
54532 144200 2009-01-02T19:28:47Z 7 6 MC
54533 164389 2009-01-31T08:57:10Z 7 6 MC
54534 164408 2009-01-31T21:15:56Z 2 6 六
Factor_D Factor_E Response Transaction_Status Month
0 20 A 1020 一月批准
1 20 H 1020 1 月批准
2 21 NaN 1020 1 月批准
3 20 H 1020 1 月批准
4 20 B 1020 一月批准
……………………
54530 20 H 1020 一月批准
54531 20 NaN 1020 1 月批准
54532 20 MCC 1020 1月批准
54533 30 MCC 1020 1月批准
54534 20 H 1020 1 月批准
[54535 行 x 10 列],
'Month-02': Account_ID Transaction_Timestamp Factor_A Factor_B Factor_C
0 3 2009-02-21T23:23:47Z 2 6 六
1 7 2009-02-14T11:35:42Z 2 6 六
2 17 2009-02-04T10:55:54Z 2 6 六
3 21 2009-02-26T09:33:05Z 2 6 六
4 24 2009-02-12T10:35:55Z 2 6 六
……………………
44375 180333 2009-02-20T08:11:51Z 8 18 轴
44376 180334 2009-02-20T08:31:06Z 8 18 轴
44377 180335 2009-02-20T08:31:27Z 10 6 DI
44378 180336 2009-02-20T08:33:28Z 2 6 六
44379 180338 2009-02-20T08:19:56Z 7 6 MC
Factor_D Factor_E Response Transaction_Status Month
0 20 B 1020 2 月批准
1 20 C 1020 2 月批准
2 20 H 1020 2 月批准
3 20 C 1020 2 月批准
4 20 G 1020 2 月批准
……………………
44375 20 NaN 1020 2 月批准
44376 20 NaN 1020 2 月批准
44377 20 NaN 1020 2 月批准
44378 35 H 1020 2 月批准
44379 20 MCP 1020 2 月批准
[44380 行 x 10 列]'
我尝试添加 if 语句,但无法运行任何内容。我所期望的只是引入具有 x 个观测值的数据框。使用上面的两个示例,第 2 个月的结果将被排除,因为它低于 50k 个观测值。
我不确定你的 if 语句有什么问题,但乍一看你是否尝试过以下方法?
import pandas as pd
import numpy as np
import glob
monthly_files = glob.glob("Module 6/data/Month_xx_data/*")
file_name = os.path.basename(monthly_files[0])
monthly_data = {}
for file_path in monthly_files:
month = os.path.basename(file_path)[:-4]
df = pd.read_csv(file_path)
if len(df)> 50000:
monthly_data[month]=df
monthly_data