如何解决在熊猫数据框中过滤不起作用
我正在尝试通过使用熊猫数据框将3个CSV合并为一个。考虑下面的例子
因此,我需要将以上csv合并为一个。这是使用以下代码实现的
<input name="name" id="waffles" onchange="handleOnChangeInput(this)"/>
即使能够将CSV合并为一个,也无法根据条件过滤行。当我尝试上述代码片段时,出现以下警告,并且data4.csv除了标题外不包含任何内容
if os.path.isfile(data1.csv) and os.path.isfile(data2.csv) and os.path.isfile(data3.csv):
df1 = pd.read_csv(data1.csv)
df2 = pd.read_csv(data2.csv)
df3 = pd.read_csv(data3.csv)
self.combined_data_frame = pd.concat([df1,df2,df3],ignore_index=True)
self.combined_data_frame = pd.DataFrame(self.combined_data_frame,columns=['col1','col2','col3'])
result = self.combined_data_frame.loc[(self.combined_data_frame['col3'] == 'FALSE')]
result.to_csv(data4.csv)
我可以知道如何解决此问题以满足我的要求,否则还有其他方法可以使用python来实现。
解决方法
- 使用
pathlib
查找文件 - 将列表理解与
pandas.read_csv
一起使用以创建数据框列表,并将其与pd.concat
组合在一起- 请注意,
'FALSE'
和'TRUE'
已分别转换为False
和True
,并且是bool
而非str
类型。 / li> - 或者,使用
pd.concat([pd.read_csv(file,dtype={'col3': str}) for file in files])
,它将将col3
保持为str
,然后仍然过滤'FALSE'
。
- 请注意,
- 使用Pandas: Boolean Indexing过滤数据框
- 过滤器必须过滤
False
,而不是'FALSE'
。
- 过滤器必须过滤
- 使用
pandas.DataFrame.to_csv
保存数据框 -
pandas
的当前版本为1.1.0
。
from pathlib import Path
import pandas as pd
# find the files
files = Path('c:/users/some_path/to_files').glob('data*.csv')
# create a dataframe of all the files
df = pd.concat([pd.read_csv(file) for file in files]).reset_index(drop=True)
# display(df)
col1 col2 col3
0 1 2 False
1 1 2 False
2 1 2 True
3 1 2 False
4 3 4 False
5 3 4 True
6 3 4 True
7 3 4 True
8 6 7 False
9 6 7 False
10 6 7 False
11 6 7 False
# filter the data for False
df_false = df[df.col3 == False]
# save the file
df_false.to_csv('false.csv',index=False)
,
您似乎在语句中加上了一组括号:
result = self.combined_data_frame.loc[(self.combined_data_frame['col3'] == 'FALSE')]
尝试改用它:
result = self.combined_data_frame.loc[self.combined_data_frame['col3'] == 'FALSE']
,
好吧,我将使用这3个数据框,将它们连接起来,并用〜过滤col3:
import pandas as pd
df1 = pd.DataFrame({
'col1':[1,1,1],'col2':[2,2,2],'col3':[False,True,False,True]
})
print(df1)
col1 col2 col3
0 1 2 False
1 1 2 True
2 1 2 False
3 1 2 True
df2 = pd.DataFrame({
'col1':[3,3,3],'col2':[4,4,4],True]
})
print(df2)
col1 col2 col3
0 3 4 False
1 3 4 True
2 3 4 True
3 3 4 True
df3 = pd.DataFrame({
'col1':[6,6,6],'col2':[7,7,7],False]
})
print(df3)
col1 col2 col3
0 6 7 False
1 6 7 False
2 6 7 False
3 6 7 False
combined_data_frame = pd.concat([df1,df2,df3],ignore_index=True)
print(combined_data_frame)
col1 col2 col3
0 1 2 False
1 1 2 True
2 1 2 False
3 1 2 True
4 3 4 False
5 3 4 True
6 3 4 True
7 3 4 True
8 6 7 False
9 6 7 False
10 6 7 False
11 6 7 False
final_data_frame = combined_data_frame[~combined_data_frame.col3]
print(final_data_frame)
col1 col2 col3
0 1 2 False
2 1 2 False
4 3 4 False
8 6 7 False
9 6 7 False
10 6 7 False
11 6 7 False
final_data_frame.to_csv('final_data_frame.csv',index=False)
最终文件根据您的预期输出( index = False )。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。