![](/img/trans.png)
[英]Python how to get the tweet data using specific word in csv file and put it in new csv file
[英]How to call a specific word from csv file using python
假設我有一個包含兩列A, B
的.csv
文件,那么如果我調用 A 列第 3 行,那么如何打印 B 列第 3 行數據。 請幫助我,因為我是代碼初學者。
我只想調用一個輸入值並從下一列打印相同的行值。
這是我的代碼:
如果消息中出現“你好”:
with open('data.csv', "r") as f:
reader = csv.reader(f)
chat = {}
for row in reader:
key = row[0]
chat[key] = row[1:]
try:
gotreply = chat[msg]
except KeyError:
gotreply = 'null'
print(gotreply)
if gotreply == 'null':
print("Sorry! I didn't understand. I'm still learning.")
else:
print("Input Again")
不確定你到底在問什么,但你可以做
import pandas as pd
foo_df = pd.read_csv('files/example.csv')
if foo_df.A[2] == "c":
print(foo_df.B[2])
我也是初學者,這是我在這里的第一篇文章,所以我會盡力幫助你。
首先,我假設你的 CSV 文件有標題,我假設你的標題被稱為“A”和“B”。
import csv
with open('test.csv', mode='r') as csv_file:
csv_reader = csv.reader(csv_file)
row_count = 1
for i in csv_reader:
if row_count == 4:
print(i[1]) # prints second column of third row
row_count += 1
可能有一種更有效的方法,但我也是這個游戲的新手。
剛開始的時候我也有這樣的疑惑。 Pandas 切片會對你有所幫助。
首先將 Pandas 模塊導入為“pd”(將 pandas 導入為 pd),因為它是最常用的形式,您會更容易適應。
import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14], ['tony', 12]]
df = pd.DataFrame(data, columns = ['A', 'B'])
這將創建一個示例數據框或簡單的“df”:
A B
0 tom 10
1 nick 15
2 juli 14
3 tony 12
使用 pandas df.loc 中最常見的切片器之一,您可以獲得所需的結果:
df.loc[2,'B']
如您所述,這將返回“B”列第 3 行。 請記住,在 Python 中,第一個索引從 0 而不是 1 開始。這就是我們使用“2”作為第三行的原因。
希望這對你有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.