我目前有以下数据框:
df1
3 4 5 6
0 NaN NaN Sea NaN
1 light medium light medium
2 26 41.5 15 14
3 32 40 18 29
4 41 29 19 42
我正在尝试返回一个新的数据框,其中只保留 Sea 列及以后的数据:
df1
5 6
0 Sea NaN
1 light medium
2 15 14
3 18 29
4 19 42
我觉得我的代码非常接近:
for i in range(len(df.columns)):
if pd.Series.any(df.iloc[:,i].str.contains(pat="Sea")):
xyz = df.columns[i] #This is the piece of code I am having trouble with
df = df.loc[:,[xyz:??]]
本质上,我想返回包含单词“Sea”的列索引,然后从该索引到数据帧的长度创建一个新的数据帧。希望这个解释是有道理的,并感谢任何帮助
最佳答案
第一步:获取列名:
In [542]: c = df[df == 'Sea'].any().argmax(); c
Out[542]: '5'
第二步:使用df.loc
索引:
In [544]: df.loc[:, c:]
Out[544]:
5 6
0 Sea NaN
1 light medium
2 15 14
3 18 29
4 19 42
如果 df.loc[:, c:]
不起作用,您可能想要回退到更明确的版本(感谢 piRSquared 的简化):
df.iloc[:, df.columns.get_loc(c):]
关于python - 从列范围返回新数据框( Pandas ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45405814/