在Python中写一个循环,当条件成立时打印出单词
Write a loop in Python to print out the words when the condition is valid
我想学习如何在 Python 中编写一个循环,以便在满足以下条件的情况下打印出字数。
# sys.setdefaultencoding() does not exist, here!
import sys
reload(sys) # Reload does the trick!
sys.setdefaultencoding('UTF8')
import tushare as ts
import pandas as pd
df = ts.get_tick_data('002428','2015-03-02')
df.head(10)
for volume in df:
if volume = 777:
print "buy signal"
elif volume = 12345:
print "wait and see"
else:
print "nothing"
好像不行我希望所有过滤后的数据都可以存储在 pandas Dataframe 格式中。
要比较项目,请使用比较运算符 (==
),而不是赋值运算符 (=
),正如 @EdChum 在评论中提到的那样,您正在迭代列。要迭代列,请使用 df[column_name]
:
for volume in df['volume']:
if volume == 777:
print "buy signal"
elif volume == 12345:
print "wait and see"
else:
print "nothing
如 Reut 所述,您需要使用“==”而不是“=”进行比较。还有循环
for volume in df:
do stuff
循环遍历数据框中的列。如果你想遍历列中的值,请这样做:
for i in df['volume']:
do stuff
如果您想将结果存储在数据框中,我会定义一个函数,然后像这样将其应用于数据框:
def my_func(volume):
if volume == 777:
return "buy signal"
elif volume == 12345:
return "wait and see"
else:
return "nothing"
df['type'] = df.volume.apply(my_func)
最后一步,如果你想将其过滤为仅 "buy signal" 行,请执行以下操作:
new_df = df[df['type'] == 'buy_signal']
使用==,而不是=。而且您并没有像您认为的那样循环遍历 df。您只是遍历列,还需要遍历行。
for index in df.index:
volume = df.loc[index,'volume']
if volume == 777:
print index, volume, "buy signal"
elif volume == 12345:
print index, volume, "wait and see"
else:
print index, volume, "nothing"
我想学习如何在 Python 中编写一个循环,以便在满足以下条件的情况下打印出字数。
# sys.setdefaultencoding() does not exist, here!
import sys
reload(sys) # Reload does the trick!
sys.setdefaultencoding('UTF8')
import tushare as ts
import pandas as pd
df = ts.get_tick_data('002428','2015-03-02')
df.head(10)
for volume in df:
if volume = 777:
print "buy signal"
elif volume = 12345:
print "wait and see"
else:
print "nothing"
要比较项目,请使用比较运算符 (==
),而不是赋值运算符 (=
),正如 @EdChum 在评论中提到的那样,您正在迭代列。要迭代列,请使用 df[column_name]
:
for volume in df['volume']:
if volume == 777:
print "buy signal"
elif volume == 12345:
print "wait and see"
else:
print "nothing
如 Reut 所述,您需要使用“==”而不是“=”进行比较。还有循环
for volume in df:
do stuff
循环遍历数据框中的列。如果你想遍历列中的值,请这样做:
for i in df['volume']:
do stuff
如果您想将结果存储在数据框中,我会定义一个函数,然后像这样将其应用于数据框:
def my_func(volume):
if volume == 777:
return "buy signal"
elif volume == 12345:
return "wait and see"
else:
return "nothing"
df['type'] = df.volume.apply(my_func)
最后一步,如果你想将其过滤为仅 "buy signal" 行,请执行以下操作:
new_df = df[df['type'] == 'buy_signal']
使用==,而不是=。而且您并没有像您认为的那样循环遍历 df。您只是遍历列,还需要遍历行。
for index in df.index:
volume = df.loc[index,'volume']
if volume == 777:
print index, volume, "buy signal"
elif volume == 12345:
print index, volume, "wait and see"
else:
print index, volume, "nothing"