我已经选择使用pandas数据帧来检索我的数据:
X = goog_data[['SPY', 'PCTChange', 'HiLo', 'ClOp', 'Lag1', 'std_30', 'std_5', 'std_15','std_100','std_200','ret_5','Pairstd5','Pairret1','Pairret5','Pairret15','Pairret30','Pairret100','Pairret100','Pairstd15','Pairstd30','Pairstd100','Pairstd200']]
现在这是可以手工完成的。现在我希望X包含5k列。我如何创建一个循环/查询(比如CSV(来附加所有这些列?(我有CSV中的所有列名(
问候
我将详细说明一个解决方案,我不完全清楚这是否是你想要的,但如果这是我认为的,解决方案应该只是读取列文件并将其转换为列表。假设我们有两件事作为输入,一个是有5k个cols的数据帧,另一个是我们感兴趣保存在单独csv:中的名为cols的csv文件
DataFrame:
col0 col1 col2 ... col4997 col4998 col4999
0 0.698623 0.932956 0.359868 ... 0.829051 0.841925 0.984595
1 0.096496 0.438520 0.324643 ... 0.045311 0.960287 0.595798
2 0.255850 0.880708 0.944889 ... 0.490338 0.310711 0.002752
3 0.950205 0.322112 0.283922 ... 0.211629 0.996797 0.614626
4 0.211844 0.580730 0.323031 ... 0.465663 0.348202 0.872415
CSV(columns.CSV(和我想要的列:
col1,col2,col513,col4153,col4900,col5000
然后:
import pandas as pd
import random
df_with5k_columns = pd.DataFrame({f"col{i}":[random.random() for _ in range(5)] for i in range(5000)})
with open("columns.csv") as columns_file:
columns_to_select = columns_file.read().replace("n","").split(",")
df_selected_columns = df_with5k_columns.loc[:,columns_to_select]
print(df_selected_columns)
将生成以下内容:
col1 col2 col513 col4153 col4900 col4952
0 0.037199 0.413641 0.790565 0.181794 0.678537 0.147004
1 0.218754 0.589376 0.138483 0.197163 0.567846 0.495609
2 0.971128 0.011847 0.015084 0.134676 0.459204 0.511046
3 0.490421 0.954400 0.524425 0.564901 0.223476 0.082343
4 0.377118 0.306438 0.651674 0.896337 0.130425 0.815342