【问题标题】:write csv in python based on sub-string condition根据子字符串条件在python中编写csv
【发布时间】:2016-09-29 15:45:38
【问题描述】:

我在数据框 (df) 中有以下 result 变量,我正在尝试为以“test”开头的那些输出一个 csv 文件

abandoned
static
test_a_1
test_b_2
abandoned
test_b_3

以下代码不起作用。提前感谢您的见解

substr="test"
if substr in df['result']:
    df.to_csv("C:/Projects/result.csv",sep=',',index=False)

【问题讨论】:

  • 当你说不工作时,你的意思是它根本没有写或写错了吗?
  • 不是写的。 substr in df['result'] 的结果为假

标签: python string csv substring


【解决方案1】:

仅仅因为“test_a_1”在列表中并不意味着“test”是, 在 Python 逻辑中。

Python 如何评估“if [string] in [list]”语句的示例:

>>> test = 'test1'
>>> testlist = ['test1', 'test2']
>>> if 'test' in test:
...     print('hi')
... 
hi
>>> if 'test' in testlist:
...     print('hi')
... 
>>>

这可行:

substr="test"
for val in df['result']:
    if substr in val:
        # Do stuff
        # And optionally (if you only need one CSV per dataframe rather than one CSV per result):
        break

【讨论】:

  • 谢谢 Iroh.. 这给出了所有结果值的输出,但我有兴趣查看 csv 中的 test_a_1,test_b_2,test_b_3 行。
  • 看起来 scomes 的解决方案适用于此,而且它是一个性感的单线。 ;)
【解决方案2】:

如果您的意思是要创建一个仅包含结果以“test”开头的行的 csv,请使用以下命令:

df[df.result.str.contains('^test.*')].to_csv("C:/Projects/result.csv",sep=',',index=False)

【讨论】:

    【解决方案3】:

    这可行:

    df['temp'] = [1 if 'test' in df['result'][k] for k in df.index else 0]
    df['result'][df['temp']==1].to_csv("/your/path", sep=',', index=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-19
      • 2018-04-21
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多