![](/img/trans.png)
[英]Pandas how to copy a column to another dataframe with similar index
[英]how to find a pandas dataframe index with a similar keyword?
我目前正在创建一个数据库,其中的表是由excel工作簿中的特定列组成的。 该算法在目录中进行迭代,并将工作表另存为pandas数据框,然后从中选择列:
df1 = pd.read_excel(file, 'sheet1')
从那里选择我需要的数据
def create_list(df1):
i = 0
list1 = []
while isinstance(df1['foo-bar'][i], int):
list1.append(df1['foo-bar'][i])
i += 1
return list1
我面临的问题是,有时列的名称不是'foo-bar'而是'foo.bar'。 有没有一种方法可以选择此列,即使它包含“ foo”? 还是选择“ foo-bar”或“ foo.bar”的“或”运算符?
我知道应该有一种使用sql的方式,但是我更喜欢用pandas。
您可以通过以下方式使用DataFrame.filter
...由于df1是一个数据帧:
df1 = df1.filter(regex=("^foo.*"))
import re
regex = re.compile("^foo.*")
columnsThatYouWant = []
for i in dataframe.columns:
if bool(regex.match(i))):
columnsThatYouWant.append(i)
然后,您可以使用其中的所有列。
这称为正则表达式。
^ foo。*表示字符串以foo开头,以任何char(“。”)结尾,且长度为(“ *”)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.